Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c - Why does i = ++i invoke undefined behaviour? [duplicate]

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.

like image 528
Qurious Avatar asked Nov 12 '14 19:11

Qurious


1 Answers

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 guarentee that the side effects of the lhs of the operator must be completed before the rhs of the statement is returned. 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. So it would look more like

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

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

like image 136
IdeaHat Avatar answered Sep 22 '22 10:09

IdeaHat