Answer the question
In order to leave comments, you need to log in
What does this code print?
In one of the projects I found a funny code fragment containing an error. The PVS-Studio analyzer noticed this error. But at first I didn't believe him. It seemed to me that the analyzer made a mistake and had already thought about launching the debugger. I looked a little more closely. No, it's really a mistake!
I changed the code a little and, using ICQ, sent the example to four programmers I know. And he asked me to write what the code below would print. All four gave incorrect answers at first.
I suggest you try to see if you can give the correct answer. What does this code print on the screen?
cout << (sizeof(char *) == 8) ? "64-bit" : "32-bit";
Answer the question
In order to leave comments, you need to log in
If I were asked in everyday life, I would be mistaken, but since. it’s immediately clear that here the question with a trick was answered correctly :-)
Read the code snippet. There was a feeling that the problem was with priorities. And so it happened.
Just use clang:
$ ./Debug+Asserts/bin/clang -fsyntax-only /tmp/zzz.cc
/tmp/zzz.cc:7:33: warning: operator '?:' has lower precedence than '<<'; '<<' will be evaluated first [-Wparentheses]
cout << (sizeof(char *) == 8) ? "64-bit" : "32-bit";
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^
/tmp/zzz.cc:7:33: note: place parentheses around the '<<' expression to silence this warning
cout << (sizeof(char *) == 8) ? "64-bit" : "32-bit";
^
( )
/tmp/zzz.cc:7:33: note: place parentheses around the '?:' expression to evaluate it first
cout << (sizeof(char *) == 8) ? "64-bit" : "32-bit";
^
( )
/tmp/zzz.cc:7:35: warning: expression result unused [-Wunused-value]
cout << (sizeof(char *) == 8) ? "64-bit" : "32-bit";
^~~~~~~~
2 warnings generated.
I myself remember from my own experience that when using a ternary operator, the condition and actions must be enclosed in brackets, because the precedence of the ternary operator is lower than that of the rotation operator.
and it also looks interesting in the opposite direction when without parentheses:
true ? std::cout : std::cerr << "????";
Now I'm looking at Google.com/analytics that quite a lot of people went to the link to see the correct answer. Here the comments are empty. Looks like I scared everyone with articles that in C++ everything is not so simple... :-)
Don't be shy. It's funny, after all.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question