I've read, Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc...) and tried understanding Sequence points on "comp.lang.c FAQ" after wasting more than 2 hours of time trying to explain the following results by gcc compiler.
expression(i=1;j=2) i j k
k = i++ + j++; 2 3 3
k = i++ + ++j; 2 3 4
k = ++i + j++; 2 3 4
k = ++i + ++j; 2 3 5
k = i++ + i++; 3 2
k = i++ + ++i; 3 4
k = ++i + i++; 3 4
k = ++i + ++i; 3 6
i = i++ + j++; 4 3
i = i++ + ++j; 5 3
i = ++i + j++; 4 3
i = ++i + ++j; 5 3
i = i++ + i++; 4
i = i++ + ++i; 5
i = ++i + i++; 5
i = ++i + ++i; 6
Question:
I want to know if all the expressions shown (in 4 groups) in above figure have undefined behavior? If only some of them have undefined behavior which ones does and which ones doesn't?
For defined behaviour expressions, kindly can you show (not explain) how compiler evaluates them. Just to make sure, if I got this pre-increment & post increment correctly.
Background:
Today, I've attended a campus interview, in which I was asked to explain the results of i++ + ++i
for a given value of i
. After compiling that expression in gcc, I realized that the answer I gave in interview was wrong. I decided not to make such mistake in future and hence, tried to compile all possible combinations of pre and post increment operators and compile them in gcc and then try to explain the results. I struggled for more than 2 hours. I couldn't find single behaviour of evaluation of these expressions. So, I gave up and turned to stackoverflow. After little bit of reading archives, found that there is something like sequence point
and undefined behaviour.