Search code examples
cincrementundefined-behavioroperator-precedencesequence-points

c - Why does i = ++i invoke undefined behaviour?


I understand that C uses the notion of sequence points to identify ambiguous computations, and that = operator is not a sequence point. However, I am unable to see any ambiguity in executing the statement

i = ++i

As per my understanding, this simply amounts to evaluating whatever is at &i, incrementing it, and storing it back at the same location. Yet, GCC flags it as under:

[Warning] operation on 'i' may be undefined [-Wsequence-point]

Am I missing something about how = functions ?

EDIT : Before marking as duplicate, please note that I have browsed other posts about sequence points and undefined behavior. None of them addresses the expression i=++i (note the pre-increment) specifically. Expressions mentioned are generally i=i++, a=b++ + ++b, etc. And I have no doubts regarding any of them.


Solution

  • You are missing something about undefined behavior. Undefined behavior simply means the compiler can do whatever it wants. It can throw an error, it can (as GCC does) show a warning, it can cause demons to fly out of your nose. The primary thing is, it won't behave well and it won't behave consistently between compilers, so don't do it!

    In this case, the compiler does NOT have to make the guarantee that the side effects of the lhs of the operator must be completed before the rhs of the statement is returned. That would look like:

    register=i+1;
    i=i+1;
    i=register;
    

    (If i started as 0 here, it would end as 1.)

    This seems funny to you but you don't think like a computer. It could, if it wants, calculate the return value and return it in a register, assign it to i, and then perform the increment on the actual value. This looks like:

    register=i+1;
    i=register;
    i=i+1;
    

    (If i started as 0 here, it would end as 2.)

    The standard gives you no guarantee that this doesn't happen, so just don't do it!