Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   What does this code print? (http://www.go4expert.com/forums/code-print-t29066/)

Karpov2007 10Sep2012 16:57

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.

xpi0t0s 11Sep2012 03:51

Re: What does this code print?
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:

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:

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

xpi0t0s 11Sep2012 03:52

Re: What does this code print?
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.

All times are GMT +5.5. The time now is 05:29.