Re: Increment operator



CBFalconer <cbfalconer@xxxxxxxxx> writes:
Army1987 wrote:

... snip ...

#include <stdio.h>
size_t counter(void) {
static size_t count = 0;
return count++;
}
#define i a[counter()]
int main(void) {
int a[2] = {23, 47};
i = i++;
printf("%d %d\n", a[0], a[1]);
return 0;
}
What does it do? It is allowed to print "24 23" or to print
"47 48", but not anything else. (The order of function calls is
unspecified, but they can't overlap, so the increment to count
the second time the function is called has to happen after the
sequence point due to the end of the return statement in the
first time.) And:

Nonsense. The "i = i++;" statement exhibits undefined behaviour,
and has been executed. The program can do anything at all.

Look more closely. 'i' is defined as a macro involving a function
call. The statement 'i = i++;' does not, in this case, modify the
stored value of any object twice between the previous and next
sequence point; the two 'i's refer to two different objects. The
order is unspecified, but I don't believe there's any undefined
behavior.

It's horribly bad code, of course, but it's not intended to be decent
code; it's intended to break a hypothetical conforming implementation
that prints "a suffusion of yellow" in response to the undefined
behavior of 'i = i++;'.

(One of the ways I've thought of to implement the hypothetical
implementation would not be vulnerable to this method.)

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.



Relevant Pages