In C++17 should this code be producing warnings?

Viewed 122

As seen on this godbolt link

clang in c++14 mode(but not in c++17) and GCC in c++17 mode produce warnings about sequencing. I assumed that in C++17 all stuff on the rhs of = is evaluated before lhs so I am not sure if the gcc warning is correct.

Code is:
static int index =0; 
void f(int* pindex){
        pindex[index] = 5;
        pindex[index] = index++;

}
int main(){

}

gcc warning is:

: In function 'void f(int*)':
:4:30: warning: operation on 'index' may be undefined [-Wsequence-point]
4 |         pindex[index] = index++;

  |                         ~~~~~^~
:4:30: warning: operation on 'index' may be undefined [-Wsequence-point]

Compiler returned: 0

note: I know that standard specifies nothing about warnings, it is just much easier to specify the question wrt warnings, than to talk about sequence point/ordering guarantees.

1 Answers

This code could produce warnings before C++17 where it was undefined behavior, but should not with C++17 or later as the behavior became defined:

  1. 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 (since C++17)

(Source)

GCC's warning is a bug. (Hopefully this is the only bug and GCC doesn't actually treat this case as UB.)

Related