Saturday, October 25, 2008

Visual Studio 2005 C++ and the ? : operator

One thing you want in C++ compilers is consistency with other C++ compilers. Especially if you are doing cross-platform development work. I want the VS C++ compiler to interpret what I tell it to do exactly the same way that gcc interprets it. That way, I don't have to special case my compilations, and I don't create a bunch of platform specific bugs in my platform neutral code. And usually, the two compilers do agree.


However, I discovered today (Friday) that if you compile something like:
double x = (false) ? 0 : 1.4;
that x will not equal 1.4 as most people (and the gcc compiler) would think, but rather it will equal 1.0. Why? Because it sees 0, interprets it as an integer and decides that if both halves of the : have to have the same type, then that type will be integer. The fact that this is in the middle of an assignment to double means nothing.

In order for x to equal the expected 1.4, you have to write:
double x = (false) ? 0.0 : 1.4;


I'm not even saying that Visual Studio is wrong. It's different from gcc which leads to platform specific bugs, and it's unexpected so the unaware coder will type in the unwanted form and not know something could possibly go wrong.

[Update: Russell Finn goes into more language lawyer parsing of this, and believes VS C++ is wrong. (I don't know Mr. Finn, I just like to read my Site Meter page to see how people get to my blog.)]


[Update 2: And don't let me get started about how VS C++ allows you to put the closing angle brackets of a nested template declaration without a space, as in:
vector<pair<string, int>> myVectorOfPairs;

]