Ramblings of General Geekery

Conditional operator fun

A good friend of mine sent me this little “gotcha” a few days ago, so I thought I’d share:

#include <iostream>

#include <string>
void main() {
int a = 0;
int* ptrA = &a;
const int b = 1 ;

const int& refA1 = (ptrA ? *ptrA : 1);
const int& refA2 = (ptrA ? *ptrA : b);

std::cout << refA1 << std::endl;
std::cout << refA2 << std::endl;

a = 42;

std::cout << refA1 << std::endl;
std::cout << refA2 << std::endl;
}

This prints:

0

0

0

0

Turns out I didn’t really know how the “?” operator figures out its overall return type because most of the time I use it with class pointers or strings or something not as complicated as integers with values of 0 or 1 or even (crazy!) 42.

In this case, the “?” operator looks at an “int” and a “const int” and figures, hey, I should really make all this a “const int”! And what better way to make a “const int” out of an “int”? Well, copy it somewhere safe, of course! So you end up with constant copies of “a”. You can print out the addresses of all the variables to see how “refA1” and “refA2” point to new places.

If you remove the “const” from “b”’s declaration, the “?” operator then looks at two integers, makes “refA2” reference “a”’s address directly, and you end up with the following output:

0
0
0
42

Conclusion: watch out when initializing a variable that could either be a constant (earth’s gravity) or a user tweakable value (gravity on the space station in level 3 of your game).