5

The following code acts differently after being compiled in linux and Visual Studio 2015.

#include <map> #include <iostream> using namespace std; int main(void) { map<int, int> map1; int keyCount = 2; for (int i = 0; i < keyCount; i++) { map1[i] = map1.size(); } for (auto value : map1) { cout << "key: " << value.first << " value: " << value.second << endl; } return 0; } 

The result in Visual Studio :

key: 0 value: 0 key: 1 value: 1 

The result in linux compiled with g++ -std=c++11 -Wall -pedantic

key: 0 value: 1 key: 1 value: 2 

I have two questions:

  1. As far as I understand c++, the VS implementation is right.
    If I change the code to:

    for (int i=0; i < keyCount; i++) { unsigned int mapSize= map1.size(); map1[i] = mapSize; } 

then it behaves like Visual Studio on both platforms.
Shouldn't the code always behave like this?

2.What Visual Studio compiler settings can I use to make sure that VS will compile the same as Linux?
I am working on Windows, but have an assignment that must work on Linux.

1
  • 3
    I wonder why you would want such a map. Commented Apr 8, 2017 at 19:49

1 Answer 1

11
map1[i] = map1.size(); 

expands to

(map1.operator[](i)) = (map1.size()); 

C++ makes no guarantees about whether operator[] or size is called first, since both are operands to the assignment expression. Both compilers are correct.

You should split your expression into two statements if you expect one behavior or the other.

Sign up to request clarification or add additional context in comments.

4 Comments

Didn't know about that. I thought the right side of assignment always gets called first.
@lazytraveller Expanded further ::operator=(map1.operator[](i), map1.size()). Parameters to a function call are not sequenced with respect to each other.
@aschelper Is the behavior still defined (in contrast to undefined, or implementation defined) if the behavior of the program depends on the (unspecified) order of operand evaluation?
C++17 may change this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.