3

I have a functions which returns true if the element is removed from the map, or false otherwise. Following is my function definition:

template <class Key, class Value>
bool HashMap<Key, Value>::remove(Key k)
{
  int result = map.erase(k);
  return (result == 1);
}

When I tried to check whether it is working or not, I found very strange behavior.

When I tried to print the results by using following syntax:

cout << boolalpha << students.remove("Sam") << " | " << students.remove("Sam") endl;

this printed false | true which should be true | false as per my knowledge. Then I tried to print it using another method:

bool b1 = students.remove("Sam");
bool b2 = students.remove("Sam");

cout << boolalpha << b1 << " | " << b2 << endl;

This printed the results as expected -> true | false. I guess this is a trick done by the compiler to optimize the code. But guesses aren't true always right ? (I am using g++ 4.8.5 compiler)

Can anyone tell me what has happen here ?

ThisaruG
  • 3,222
  • 7
  • 38
  • 60
  • 1
    disagree with this choice of duplicate really, the code is NOT undefined behaviour – M.M Dec 07 '16 at 14:08

2 Answers2

6

The order of argument evaluation during function calls in unspecified. This applies to std::cout as well, because std::cout << a << b; is simply shorthand notation for

operator<<(operator<<(std::cout, a), b);
Community
  • 1
  • 1
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
4

The order of evaluation is unspecified here (cfr. order of evaluation) as in function calls (which actually is)

cout << boolalpha << students.remove("Sam") << " | " << students.remove("Sam") endl;

while is defined here

bool b1 = students.remove("Sam");
bool b2 = students.remove("Sam");

cout << boolalpha << b1 << " | " << b2 << endl;
Marco A.
  • 43,032
  • 26
  • 132
  • 246