Warm tip: This article is reproduced from serverfault.com, please click
c

Why does the & operator only work in variables and not in inline statements

发布于 2020-11-27 23:41:25
printf("%i\n",2&2==2);

This should print out a 1 but I get a 0, why is this?

int ans=2&2;
printf("%i\n",ans==2);

This prints a 1, how come the first way does not work? This is the case with if statements as well

Questioner
BackSpace7777777
Viewed
0
Bill Lynch 2020-11-28 08:35:05

The order of operations is different than you think it is. A correct way to write it in a single line would be:

printf("%i\n", (2 & 2) == 2); // Prints 1