With -Wsequence-point
enabled, GCC should warn user when undefined behavior code is spotted. For example
b = a + ++a;
should be noticed by GCC and should be reported as "undefined behavior" code (because ISO C doesn't specify the order of evaluating operands for addition).
However, I played with the syntax and I tried this one:
int *a = malloc(sizeof(int) * 2);
a[0] = 1;
printf("%d\n", *(a + (*a)++ - *a));
Of course, I got the warning
warning: operation on '*a' may be undefined [-Wsequence-point]
which is what I expected, because the value of *a
(which is a[0]
) may be incremented or may not be while processing the third operand. But, I tried the following one:
int *a = malloc(sizeof(int) * 2);
a[0] = 1;
printf("%d\n", *(a + (*a)++ - 1));
I was surprised because I got no warnings. Shouldn't this be UB too? I mean, according to ISO C99, post increment operation may be evaluated at any point durring expression evaluation (except for comma operators and ternary operators). In my latter example, I am not incrementing pointer, but instead the integer it points to. So, accordning to the standard, it can be incremented at any point (which means that it can be incremented after whole expression is evaluated), so the program may print both 1
or 2
, right?
Why doesn't GCC throw any warnings? Or did I miss something? Did I wrongly understand the specs?