Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

This question already has an answer here:

The following code snippet in C:

i=i++;

has undefined behaviour according to a book.But my logic is this:

Since ++ operator has more precedence than = operator,it should be evaluated first,so i++ should b computed first,and then the assignment part.

Why is my logic wrong?

share|improve this question
    
You need to go read up on sequence points (parashift.com/c++-faq/sequence-points.html). The answer is largely academic however, please never write that in actual code. –  Matt D Jun 21 '13 at 11:31
    
@MattD,thanks a lot for the link on sequence points,but I still don't get the answer to my question –  user1369975 Jun 21 '13 at 12:06
    
Read the link posted by jan, It explains the problem, and why sequence points are important to it. –  Matt D Jun 21 '13 at 12:07
    
@JanHudec,that is not a duplicate question,it asked why the standard couldn't have been defined in a certain way he thought,but my question is that why my logic about the question is wrong –  user1369975 Jun 21 '13 at 12:08
1  
The first line of the duplicate link is "It's undefined because the it modifies x twice between sequence points". This invalidates your logic. As the problem isn't precedence. the problem is how sequence points work, and how operations are committed. –  Matt D Jun 21 '13 at 12:28
show 1 more comment

marked as duplicate by Jan Hudec, superM, Kilian Foth, Glenn Nelson, BЈовић Jun 21 '13 at 12:23

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer

Your reasoning goes wrong in the fact that the sub-expressioni++ has two steps that don't necessarily have to be executed immediately after each other.

  • The first step is yielding the original value of i for further computations
  • The second step is storing the new (incremented) value back to i

There is nothing preventing an optimising compiler from putting other computations (like the assignment to i) in between those two steps. As storing a value in i can even take multiple machine instructions, the instructions from the assignment and from storing the result of the increment could become interleaved with each other, possibly yielding an end result that neither resembles the incremented nor the original value.

share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.