G
Guest
no. Once I realised the program contained unnecessary undefined behaviour, I'd remove it. No guesses necessary.
OK, so we fix it so that the result is ....? Any guesses?
"a suffusion of yellow"
Changing the erroneous code so that it stays within the rules:
int i = 0;
int t1,t2,t3;
t1=++i;
t2=++i;
t3=++i;
i=t1+t2+t3;
printf("%d",i);
Now gives a valid result. Which happens to coincide with the OP's
expectations, and with what I said it *ought* to be (for which I was called
a 'nitwit', even though I went on to explain why the OP wasn't getting that
result),
a bit harsh but you plainly don't understand what "undefined behavior" means.
and in fact with what most of my compilers were already giving me
anyway; presumably they were already using code along the same lines!)
a more mysterious one was posted recently. It was only by looking at the assembler was anyone able to explain the result.
However, the interesting question is, why anyone - outside c.l.c obviously -
might think the output of the OP's original code might be 6, rather than any
other number (or any other manifestation, according to previous threads
along the same lines).
i = (i + 3) + (i + 3) + (i + 3)
i = i + 3
Or, are we not allowed to think or guess anything at all, simply because the
C standard says the original expression has undefined behaviour?
no. If the implementor decides to tell you what the behaviour is- and guarantees the behaviour then you might trust that. Some UB is commonly
used,
unsigned *reg = (unsigned*)0x8010;
*reg = 0x01; // fire lasers
but I can see no point in silly code like this threads