I'm using Codeforces custom test. When compile and run, this code yield different results,
#include <bits/stdc++.h>
using namespace std;
int k;
map<int,int> a[2];
int bar () {
return ++k;
}
void foo () {
a[k][1] = bar();
}
int main() {
k=0;
foo ();
cout<<a[0][1]<<" "<<a[1][1]<<endl;
return 0;
}
//GNU G++11, GNU G++14 yield "1 0"
//GNU G++17 yield "0 1"
Is there any issue about this? What is expected behavior is this case?
See This answer in stack-overflow.
a[k][1]=++k;
is undefined behavior for c++ versions less than c++17: The left hand side of the = operator can be executed before or after the right hand side, basically anything can happen when undefined behavior. In c++17, it's guaranteed that the right side will be executed before the left side.Thank you.