Question

I'm confused with the postfix and prefix operator precedence in C, any help and hints would help.

I'll paste my test code here:

#include <stdio.h>

int a = 0;

int main(int argc, char *argv[])
{
   if (++a & 0x01) // prefix version
   // if (a++ & 0x01) // postfix version
   {
      printf("++ first\n");
   }
   else
   {
      printf("& first\n");
   }
   return 0;
}

I can now understand that in the postfix version, although postfix ++ has a greater precedence, a++ would return 0 here to & with 0x01 and would increment a's value after this expression.

But what I can't understand is why in the prefix version, why ++a is first evaluated? the operator precedence table indicates that prefix ++ and & has the same precedence, and in addition, their associativity is right-to-left. Doesn't this means & should be evaluated first?

EDIT: the chart I'm using: C Operator Precedence Table

Was it helpful?

Solution

Check your precedence table again. I believe you may be getting confused with the unary address operator & and the binary bitwise-and operator &.

See: http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence

With this interpretation, you increment a before applying the bitwise-and.

OTHER TIPS

For prefix/postfix:

++a -> (retrieve + increment), then use the value.

a++ -> (retrieve), use the value, (increment)

Precedence: This in this way:

((++a) & 0x01) , both ( & and ++ ) are in different expression.

Hope it helps to some extent to understand.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top