There is no need for other explanations or suggestions. It IS undefined behaviour because the C (or C++) standard says that it is and since the compiler is free to do absolutely anything once undefined behaviour is invoked any result could occur. For instance on my system using the exact same code I get the output
24, 13, 14, 14
The cause of the undefined behaviour in this case is that you have accessed a variable (a) more than once between sequence points where one or more or those accesses are for a write operation.
i m not sure about the first part b=++a + ++a.
In this case when u say ++a, it just increments 'a' at its place by 1. a+b is evaluated by compiler in postfix manner.so,at the end both operator are having value 12.so,24.
but i m sure about printf part. In this case values are passed from left to right on to the stack.so ++a is evaluated first thats why 13,then a ,again 13,then a++ which will be evaluated after this statement so again 13 & b which is 24.
If u try to print a now,it will be 14.
zacksoniar, I am afraid you are wrong on the first count because the C/C++ standards specifically say that trying to access a variable more than once between sequence points were 1 or more of the access is to write (change the variable value) results in undefined behaviour.
Since the result of the expression is undefined behaviour the result you give could happen but so could any other result. The fact is that the value of such expressions changes from compiler to compiler and system to system, precisely because it is undefined behaviour. Such expressions should be avoided (and are generally unnecessary anyway).
Unfortunately you don't fair much better when explaining the printf behaviour. The order of evaluation of parameters in a function call is implementation defined. That is the implementation can do it any way it chooses but must document what the method is. Commonly parameters are evaluated either left to right or right to left. What you say may be true about the platform you are using but if you got into the habit of relying on that and then moved to a platform where it was different then you would suddenly find behaviour that you relied on didn't work as expected.
You should avoid implementation defined behaviour if at all possible and if it isn't possible it should be confined to a file by itself and clearly documented in case the software needs to be ported to another system.
I agree with u Banfa,but I tried to explain it with respect to what output whizgirl58 has specified.The compiler she is using,must be following right-to-left evaluation(++a part first).so its according to her compiler.I m still not sure about first part(b=++a + ++a).She must consider what u have said & then consider my opinion
Comment