The priority of logical operators in C

Possible duplicate:
why does "++ x || ++ y && ++ z" first calculate "++ x"? however, the & & operator is higher than the ||

If you look at the C priority table, you will see that && has a higher priority than ||

But look at the following code:

a=b=c=1;

++a || ++b && ++c;

printf("%d %d %d\n",a,b,c);

It prints “2 1 1”, which means that “++ a” is evaluated first, and as soon as the program sees TRUE there, it stops right there, because what's on the other side || irrelevant.

But since && has a higher priority than ||, shouldn't you evaluate "++ b && ++ c" first and then the result is again included in "++ a || result"? (in this case, the program will print "1 2 2").

+5
source share
5 answers

Just try to represent it with parentheses:

++a || ++b && ++c;

equally

(++a) || (++b && ++c);

which is evaluated from left to right.

if && & and || will have the same priority, it will look like

(++a || ++b) && (++c);
+13
source

The priority rules say that they will be evaluated as follows:

++a || (++b && ++c);

, , , . .

+6

- . . ++a || ++b && ++c

  • ++ a
  • 1 , ++ b && ++

++a || (++b && ++c); , ++a ++b && ++c .

+2

&& has higher precedence .

if( !++a ) {
    ++b && ++c;
}
0
source

Your example ++a || ++b && ++cmatches ++a || (++b && ++c).

0
source

All Articles