What does this code print?

Discussion in 'C++' started by Karpov2007, Sep 10, 2012.

  1. Karpov2007

    Karpov2007 Banned

    Joined:
    Oct 14, 2007
    Messages:
    66
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    scientific adviser of OOO "Program Verification Sy
    Location:
    Russia, Tula
    Home Page:
    http://www.viva64.com/
    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.
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    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";
    
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    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.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice