What does this code print?

Banned
10Sep2012,16:57   #1
Karpov2007's Avatar
I have found a nice code fragment with an error in one project. The PVS-Studio analyzer noticed it. But I didn’t believe it at first: I thought the analyzer had been mistaken and considered launching the debugger. Then I looked closer. Oh yes, an error indeed!

I changed the code a bit and sent it to four programmers, acquaintances of mine, via ICQ. I asked them to tell me what that code printed. All four of them gave wrong answers at first.

I suggest that you try to give a correct answer. What does this code print?


Code:
cout << (sizeof(char *) == 8) ? "64-bit" : "32-bit";

Of course, the long introduction has alerted the readers, so you have most likely found the right answer.
Mentor
11Sep2012,03:51   #2
xpi0t0s's Avatar
It's a good example of why brackets should be used even if you think you know what you are doing. This code works as expected:
Code:
cout << ((sizeof(char *) == 8) ? "64-bit" : "32-bit");
and displays "64-bit" if the program is built for a 64-bit CPU and "32-bit" if 32-bit.

Without the braces it displays 1 for 64-bit and 0 for 32-bit and is equivalent to:
Code:
(cout << (sizeof(char *) == 8)) ? "64-bit" : "32-bit";
Mentor
11Sep2012,03:52   #3
xpi0t0s's Avatar
Still, I'm surprised that whoever wrote the original code didn't spot that it displayed 1 or 0 instead of 64-bit or 32-bit in their testing.