true != true?

A co-worker was struggling with an urgent bug, and came by my office to ask an odd question.

Is it possible for true != true in C++?

Last time I checked, 1 is equal to 1. So I stopped by her cubical to see this magical event.

Is it true?

She told me that the code has been recompiled from scratch, and both debug and release build exhibit the same behavior.

Variable b is initialized to be true, and Visual Studio run-time checks didn’t catch anything strange.

Stepping through the code in Visual Studio 9, here’s what we saw.

Variable b is true, so it should pass the satisfy the first condition.

The first case failed, and went to the false case instead.

Wow, she’s right. This is quite something.

Diving in

C++ is a language well designed to shoot your foot. In the standard, bool is an integral type that may be 1 or more bytes, and can be either true, false or undefined.

Experience tells me that very likely, b is not true. Visual Studio is not displaying the truth.

To show this, just print out the value of b.

std::cout << std::hex << b << std::endl;

prints 0xcd

Ah ha, so b is an uninitialized variable, and falls under the category of “undefined” in the standard.

Code

Visual Studio does have runtime checks against accessing uninitialized variables, but it can be easily fooled.

Runtime check fails below for VC 8, 9, and 10.

<pre>#include <iostream>

struct SBool {	bool b; };
SBool GetBool()
{
	SBool s;
	return s;
}
int main()
{
	bool b = GetBool().b;
	if(true == b)
	{
		std::cout << "true"<< std::endl;
	}
	else
	{
		std::cout << "false" << std::endl;
	}
	std::cout << std::hex << b << std::endl;

	return 0;
}

One thought on “true != true?

  1. Lockal says:

    Yet another example when true != true:

    #include
    #include

    #define true nan(“”)

    int main()
    {
    if (true != true)
    fputs(“WTF?\n”, stderr);
    }

Leave a comment