Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why chained prefix increment/decrement for builtin type is not UB for C++?

In cpprefernce.com example for prefix increment there is such code:

int n1 = 1;
...
int n3 = ++ ++n1;

Why chained increment in this case does not lead to UB? Is rule for at most once modified not violated in this case?

like image 582
Slava Avatar asked Feb 17 '16 18:02

Slava


1 Answers

In C++11 and later, UB occurs when there are two writes or a write and a read that are unsequenced and access the same memory location. But ++x is equivalent to x+=1, so ++ ++n1 is equivalent to (n1+=1)+=1, and here the reads and writes happen in a strict sequence because of the properties of assignment and compound assignment operators: first n1 is read, then one plus the original value is written, then the resulting value is read again, then one plus that value is written back.

In C++03, this was UB, because of the old rule you allude to: there is no sequence point between the two modifications. But in C++11 there are no longer any sequence points; instead there is the "sequenced before" partial order.

like image 178
Brian Bi Avatar answered Sep 18 '22 08:09

Brian Bi