Order of operations

Hi C++ forum:
Recently I ran into a very strange error. I have a class with overloaded operator = and [] with type signatures

Variant& Variant::operator=(const bool &val);
Variant& Variant::operator[](const char* key);

Consider the following statement, where foo is my class

foo["key1"] = (bool)foo.someFunctionThatReturnsBool();

Now with the latest GCC, the statement executes correctly:
1. It first evaluates the right hand side
2. then it calls the = operator with the value obtained

But with GCC 4.2.0, the statement executes like so:
1. It first gets a reference to foo["key1"]
2. then it evaluates the RHS
3. then it calls the operator =

but the problem is foo["key1"] (overloaded operator []) changes a member variable which changes the output value of someFunctionThatReturnsBool() and this is causing problems with the older GCC.

Why do the two GCC versions interpret/compile the same statement differently? Do you know what the correct (C++ standard) way to interpret that statement is, or is this just some kind of GCC quirk?

Thanks
Andrew L.
AFAIK, the order of evaluation is undefined.
Do you know what the correct (C++ standard) way to interpret that statement is


The standard says this is undefined. The compiler is free to evaluate the statements in any order is sees fit as long as it follows the operator precedence rules (ie, it can't evaluate the assignment operator before the [] operator). You just happened to be getting "lucky" in the newer gcc.

Personally, I think you should reconsider your design. Your [] operator probably shouldn't have this kind of wacky side effect.

One way to get around this is to split this up across two sequence points so you can be sure things are evaluated the way you want. You could do this like so:

1
2
bool v = foo.someFunctionThatReturnsBool();
foo["key1"] = v;
Topic archived. No new replies allowed.