>
>
What does this code print?

Andrey Karpov
Articles: 671

What does this code print?

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?

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.

This code will print one or zero. The expression in parentheses is calculated first. Depending on the compilation mode you get either true or false. The next operation to be executed is the call of an overloaded operator <<. As a result, either number 0 or 1 will appear on the screen.

Then, the object of the ostream type will be implicitly cast to the bool type. And finally the ternary operator '? :' will be executed. But this operation doesn't do anything.