ThisaruG
ThisaruG

Reputation: 3412

Strange behavior in C++ compiler - Optimization?

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 ?

Upvotes: 3

Views: 257

Answers (2)

Marco A.
Marco A.

Reputation: 43662

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;

Upvotes: 4

Vittorio Romeo
Vittorio Romeo

Reputation: 93274

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);

Upvotes: 6

Related Questions