Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++17 sequencing: post-increment on left side of assignment

The C++17 standard revised the definitions of the order of operations for the C++ language by a rule stating, to the effect:

In every simple assignment expression E1=E2 and every compound assignment expression E1@=E2, every value computation and side-effect of E2 is sequenced before every value computation and side effect of E1

However, when compiling the following code in GCC 8.1 with -std=c++17 and -Wall

int v[] { 0,1,2,3,4,5,6,7 };
int *p0 = &v[0];
*p0++ = *p0 + 1;
cout << "v[0]: " << v[0] << endl;

I get the following warning:

main.cpp:266:8: warning: operation on 'p0' may be undefined [-Wsequence-point]
     *p0++ = *p0 + 1;
      ~~^~

The output is:

v[0]: 1

And the question: is the warning erroneous?

like image 440
ThomasMcLeod Avatar asked Dec 24 '22 03:12

ThomasMcLeod


1 Answers

And the question: is the warning erroneous?

It depends.

Technically, the code in question is well-defined. The right-hand side is sequenced before the left-hand side in C++17, whereas before it was indeterminately sequenced. And gcc compiles the code correctly, v[0] == 1 after that assignment.

However, it is also terrible code that should not be written, so while the specific wording of the warning is erroneous, the actual spirit of the warning seems fine to me. At least, I'm not about to file a bug report about it and it doesn't seem like the kind of thing that's worth developer time to fix. YMMV.

like image 58
Barry Avatar answered Jan 05 '23 15:01

Barry