Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

Блог пользователя WeZoomIn

Автор WeZoomIn, история, 5 лет назад, По-английски

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?

  • Проголосовать: нравится
  • +6
  • Проголосовать: не нравится

»
5 лет назад, # |
  Проголосовать: нравится +27 Проголосовать: не нравится

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.