+ 1

What are sequence points in C?

I came across a few programs which produces different results on different compiler like using postfix operator two times on the same variable in a single statement (j=i++ + i++). I look for answer in the web and found out that updating a single variable in the same sequence point results into undefined behaviour. I'm not able to fully understand the concept of sequence points.

4th Jun 2018, 7:32 AM
Nikhil Sharma
Nikhil Sharma - avatar
3 Réponses
+ 1
"A sequence point defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed." ~ Wikipedia Imagine squence point as one statement of code. If you did something like: j= i++; //One sequence point j += i; // 2nd sequence point j += i++; // 3rd sequence point Then code would work without undefined behaviour. But since you merge these three statements into one (squence point) it gives you undefined behaviour, because compiler don't know which value to increment and which to add first. Edit: i++ + i; would cause undefined behaviour see post of Nikhil Sharma. I edited my post accordingly
4th Jun 2018, 1:43 PM
Jakub Stasiak
Jakub Stasiak - avatar
0
Jakub Stasiak Your first instruction j=i++ + i; will give undefined behaviour because suppose i=3 then your statement could be j=3+3 or j=3+4 because there is no sequence point in that statement so ++could be performed before or after reading second i variable.
5th Jun 2018, 5:25 AM
Nikhil Sharma
Nikhil Sharma - avatar
0
Nikhil Sharma Yes, I saw that after posting and forgot to change it. Thanks ^^
5th Jun 2018, 6:56 AM
Jakub Stasiak
Jakub Stasiak - avatar