"&&" and "and" operator in C

haccks picture haccks · Jun 28, 2013 · Viewed 8k times · Source

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

C Code:

#include <stdio.h>

int gcd(int x, int y);

int main()
{
    int m,n,temp;
    printf("Enter two integers: \n");
    scanf("%d%d",&m,&n);
    printf("GCD of %d & %d is = %d",m,n,gcd(m,n));
    return 0;  
}

int gcd(int x, int y)
{
    int i,j,temp1,temp2;

    for(i =1; i <= (x<y ? x:y); i++)
    {
        temp1 = x%i;
        temp2 = y%i;
        if(temp1 ==0 and temp2 == 0)
            j = i;
    } 
    return j;         
}

In the if statement, note the logical operator. It is and not && (by mistake). The code works without any warning or error.

Is there an and operator in C? I am using orwellDev-C++ 5.4.2 (in c99 mode).

Answer

Shafik Yaghmour picture Shafik Yaghmour · Aug 12, 2013

&& and and are alternate tokens and are functionally same, from section 2.6 Alternative tokens from the C++ draft standard:

Alternative Primary
    and       &&

Is one of the entries in the Table 2 - Alternative tokens and it says in subsection 2:

In all respects of the language, each alternative token behaves the same, respectively, as its primary token, except for its spelling. The set of alternative tokens is defined in Table 2.

As Potatoswatter points out, using and will most likely confuse most people, so it is probably better to stick with &&.

Important to note that in Visual Studio is not complaint in C++ and apparently does not plan to be.

Edit

I am adding a C specific answer since this was originally an answer to a C++ question but was merged I am adding the relevant quote from the C99 draft standard which is section 7.9 Alternative spellings <iso646.h> paragraph 1 says:

The header defines the following eleven macros (on the left) that expand to the corresponding tokens (on the right):

and includes this line as well as several others:

and    &&

We can also find a good reference here.

Update

Looking at your latest code update, I am not sure that you are really compiling in C mode, the release notes for OrwellDev 5.4.2 say it is using GCC 4.7.2. I can not get this to build in either gcc-4.7 nor gcc-4.8 using -x c to put into C language mode, see the live code here. Although if you comment the gcc line and use g++ it builds ok. It also builds ok under gcc if you uncomment #include <iso646.h>