Friday, September 12, 2008

a++ for int vs short in C

Using a particular C compiler, the expression 'printf("%d\n", (a++ -
--a));' printed '0' if 'a' was int, and '1' if 'a' was short. Why?

1 comment:

Kundan said...

The C specification does not say whether post/pre-increment/decrement
are evaluated before the particular variable access or before the
expression access. Apperantly the compiler evaluated a++ inline for
int (and long), and evaluated a++ before the expression for
short (and char).

For int, it became: (a++)-(--a), which is ((a1=a,a=a1+1,a1)-(a=a-1)),
left to right.

For short, it became: (b=((a1=a)-(a=a-1)),a=a1+1,b) left to right.

Note how a=a1+1 step is either in first part or after evaluating the
whole expression.