views:

132

answers:

4
+3  A: 

Undefined behaviour:

s=++a + ++a;

Anything can happen when undefined, so your behaviour is perfectly valid.

Secure
Missing the point.
Blindy
@Blindy: Perhaps you could explain, exactly, what point is missing.
Greg Hewgill
He's missing the point that regardless of this line, both the OP's versions of the code should (and do) return the same thing on the same compiler. That's what the question is actually about.
Blindy
@Blindy: That's not what the question says. 14 != 13.
Greg Hewgill
No, Blindy, I think you're missing the point: undefined means exactly that, undefined. It's perfectly acceptable for even the first program on its own to give a totally different, random, answer every time you run it. It's also perfectly acceptable for the compiler to format your hard disk, or for space to fold in on itself and form a singularity. The fact that you have the same int going in and the same statement is irrelevant. The compiler is free to do whatever it wants. That's why you _don't use undefined behaviour!_
paxdiablo
@Blindy 2 lines with `s = ++a + ++a` don't actually have to behave the same, because the behaviour is undefined by the standard.
Scott Wales
+1  A: 

I'd suspect this is an artifact of compiler optimisation, in the first example a is known so the compiler optimises the preincrements to occur before the addition. In the second example the value is unknown and the compiler does not optimise the sequence causing it to complete left to right. This may be a function of your specific compiler and it would need to be looked at specifically.

Lazarus
+1  A: 

Undefined behaviour. Change it, or you risk being attacked by raptors.

Visage
A: 

hi budy this coding working correctly in VI compiler ..