“&&” and “and” operator in C

前端 未结 8 1871
名媛妹妹
名媛妹妹 2020-11-30 10:05

I am trying to calculate the Greatest Common Denominator of two integers.

C Code:

#include 

int gcd(int x, int y);

int main()
{
             


        
8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 10:28

    If the code in your question compiles without errors, either you're not really compiling in C99 mode or (less likely) your compiler is buggy. Or the code is incomplete, and there's a #include that you haven't shown us.

    Most likely you're actually invoking your compiler in C++ mode. To test this, try adding a declaration like:

    int class;
    

    A C compiler will accept this; a C++ compiler will reject it as a syntax error, since class is a keyword. (This may be a bit more reliable than testing the __cplusplus macro; a misconfigured development system could conceivably invoke a C++ compiler with the preprocessor in C mode.)

    In C99, the header defines 11 macros that provide alternative spellings for certain operators. One of these is

    #define and &&
    

    So you can write

    if(temp1 ==0 and temp2 == 0)
    

    in C only if you have a #include ; otherwise it's a syntax error.

    was added to the language by the 1995 amendment to the 1990 ISO C standard, so you don't even need a C99-compliant compiler to use it.

    In C++, the header is unnecessary; the same tokens defined as macros by C's are built-in alternative spellings. (They're defined in the same section of the C++ standard, 2.6 [lex.digraph], as the digraphs, but a footnote clarifies that the term "digraph" doesn't apply to lexical keywords like and.) As the C++ standard says:

    In all respects of the language, each alternative token behaves the same, respectively, as its primary token, except for its spelling.

    You could use #include in a C++ program, but there's no point in doing so (though it will affect the behavior of #ifdef and).

    I actually wouldn't advise using the alternative tokens, either in C or in C++, unless you really need to (say, in the very rare case where you're on a system where you can't easily enter the & character). Though they're more readable to non-programmers, they're likely to be less readable to someone with a decent knowledge of the C and/or C++ language -- as demonstrated by the fact that you had to ask this question.

提交回复
热议问题