Strange behaviour; how == works?

Is this behaviour correct?

  • yes
  • no
  • I don’t know

0 voters

Hello,
today I’ve noticed a behaviour that I cannot understand.

The following bit operations:
1 & 1 gives 1
2 & 2 gives 2
and so on

but when analyzing conditions
(1 & 1 == 1) is true
but
(2 & 2 == 2) is false !

And then I have noticed that such conditions with odd numbers give true but with even numbers give false.
For example such simple program:


#include <stdio.h>

int main()
{
int i;
for (i=0; i<10; i++)
{
printf("%d → %d\n",i, i & i == i);
}
return 0;
}


Who knows how == operator works? Is everything allright with gcc? I tried do this in another OS using gcc and it is the same but eg. Java gives TRUE when condition is true. What’s wrong. Maybe ANSI tells something about it.
If someone has any idea, please let me know.

You should do some reading on C operator and their priority.

== gets evaluated BEFORE 1 &1, hence your code actually does:

( 1 & ( 1 == 1 ) )

Here 1 == 1 is true (which is implemented as 1 in watcom C, then 1 & 1 gives one which is true.

( 2 & ( 2 == 2 ) )

Here 2 == 2 is true then that gets resolved to 2 & 1 which is false.

msdn2.microsoft.com/en-us/library/2bxt6kc4

  • Mario