In the book called gnu c manual I read that the following code has an undefined behavior
`i=++i +1`; Because since the variable i is modified more than once between the sequence point,it is not sure that what value will 'i' have..But it is evident that the final value in 'i'(if i=1) would be 3..Can someone please clear my doubt..

ambreen.altafhussain commented: i=++i+1 shows pre and post both increments and answer will be 3 if i=1. +0

In the book called gnu c manual I read that the following code has an undefined behavior `i = ++i + 1;` Because since the variable i is modified more than once between the sequence point,it is not sure that what value will 'i' have.

That's correct.

## All 4 Replies

i=++i+1 shows pre and post both increments and answer will be 3 if i=1.

In the book called gnu c manual I read that the following code has an undefined behavior `i = ++i + 1;` Because since the variable i is modified more than once between the sequence point,it is not sure that what value will 'i' have.

That's correct.

But it is evident that the final value in 'i'(if i=1) would be 3.

It's not evident at all. Just because you can't think of a way the result could be anything other than 3 doesn't mean there isn't a way, or that a compiler won't handle things differently than you expect. In the case of the increment operator, it's only guaranteed that the write happens before the next sequence point. If that write is delayed until after the addition of 1 to i, you'll get a result of 2:

``````; Conforming assembly code for i = ++i + 1
mov r1, i
inc r1
mov r2, 1
mov i, r2
mov i, r1 ; Oops, the write for ++ was not where you expected
``````

This is quite different from the evaluation you were expecting that produces a result of 3:

``````; Conforming assembly code for i = ++i + 1
mov r1, i
inc r1
mov i, r1 ; The write for ++ is were you expected
mov r2, 1