1. ## Result of expression!!!!!

Hello...

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 2. 3. Originally Posted by rohitms Hello...

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:
Code:
```a = (a+1);
a = a + a;
++a;
a++;```
But remember this is only one possible interpretation of the statement (because any result is valid).

On the other hand, if you substituted other variables for a, like this:
Code:
`a = (++b) + (c++);`
you might get machine code which looks something like this:
Code:
```a = (b+1);
a = a + c;
++b;
c++;```
(I know, that's C, not machine code, but imagine that each statement gets compiled to a single instruction or two).

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. 4. Welcome to the forum, rohitms!  5. 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):
Code:
```int x = a + 1;
int y = a;
a = x + y;
a = x;
a = y + 1;```
Result: 6

How about using only one temporary variable (or register) for the post-increment:
Code:
```a = a + 1; // ++a
int x = a; // result of a++
a = a + x;
a = x + 1; // a++```
Result: 7

If the post-increment is calculated before the pre-increment the result changes again:
Code:
```int x = a; // result of a++
a = a + 1; // ++a
a = a + x;
a = x + 1; // a++```
Result: 6

What if we do this instead?
Code:
```int x = a; // result of a++
a = a + 1; // ++a
a = a + x;
a = a + 1; // a++```
Result: 12

Or another legal (but unlikely) interpretation:
Code:
`a = 400;`
Result: 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. Popular pages Recent additions 