Hello...
Please analyze the following expression..
Suppose, a = 5;
a = (++a) + (a++);
Final value of a is 13 ...
but it should be 11 na...
Somebody please explain how is it 13....??
Regards,
Rohit M S
Hello...
Please analyze the following expression..
Suppose, a = 5;
a = (++a) + (a++);
Final value of a is 13 ...
but it should be 11 na...
Somebody please explain how is it 13....??
Regards,
Rohit M S
It's 13 with your compiler on your operating system with a specific compiler version and build flags. Other compilers/versions/systems/flags could give other values. Anything can be considered valid, and it's well within any compiler's right to toast your hard drive for using undefined behavior.
It's probably dangerous for me to explain why you got the result you did, but I can't help myself...
I'm guessing that your compiler is generating machine code that takes a+1 (6), adds 5 to it (11), assigns that value back to a, and then increments a twice, much like the following well-defined code:
But remember this is only one possible interpretation of the statement (because any result is valid).Code:a = (a+1); a = a + a; ++a; a++;
On the other hand, if you substituted other variables for a, like this:
you might get machine code which looks something like this:Code:a = (++b) + (c++);
(I know, that's C, not machine code, but imagine that each statement gets compiled to a single instruction or two).Code:a = (b+1); a = a + c; ++b; c++;
Since each variable (a, b, and c) is being modified only once between sequence points, these statements are valid and well-defined and give the expected results.
Welcome to the forum, rohitms!
I added it up in my head and got 13, FWIW.
Just so you don't think that 11 or 13 is "the" correct result, here are other valid interpretations of the expression.
Here's one interpretation using temporary variables at the machine code level (perhaps they're CPU registers):
Result: 6Code:int x = a + 1; int y = a; a = x + y; a = x; a = y + 1;
How about using only one temporary variable (or register) for the post-increment:
Result: 7Code:a = a + 1; // ++a int x = a; // result of a++ a = a + x; a = x + 1; // a++
If the post-increment is calculated before the pre-increment the result changes again:
Result: 6Code:int x = a; // result of a++ a = a + 1; // ++a a = a + x; a = x + 1; // a++
What if we do this instead?
Result: 12Code:int x = a; // result of a++ a = a + 1; // ++a a = a + x; a = a + 1; // a++
Or another legal (but unlikely) interpretation:
Result: 400Code:a = 400;
As anduril462 and I pointed out already, the result is undefined, so any result that the compiler produces for your original statement is valid.