Hi I just had a C++ Interview - it did not go well - I was hoping I could get some questions cleared up so I can perhaps learn if I get another one.
The question was something like this:
int a = 2;
int b = 4;
????? a | b;
????? a || b;
The question mark I cant exactly remember the syntax but it was a printf asking for the result - am i right in the first is a BITWISE OR and the second is LOGICAL OR - what would the results of these be?
The first one is a bitwise or. Here's a binary representation of what goes on:
2 == 00000010
4 == 00000100
2 | 4 == 00000110 == 6
As for the logical or, it will print 1 if the expression is true, and 0 is it's false. Actually it will print 2, because there's no parens, and because of short circuit evaluation. If there were, in C++, it would print true or false directly.
Thanks for your response Guys - filipe - yeah it actually just hit me when I came out that a BitWise Or is just a fancy addition - blanked in the interview.
Hmm. After I wrote that post, I thought maybe I could have made a mixup with C. I was at work, with no compiler (I'm not a professional programmer), but I recently found a copepad.org that allows you to compile and get the output online. When I compiled it there, (2 || 6) printed as true, and 2 || 6 printed as 2.
Now at home, I compiled it with Visual C++ and GCC. Both output 1 for the first expression, and 2 for the second. Even for the expression 2 && 6 both compilers will output 2. So there's really no short circuit evaluation happening, but it doesn't evaluate to a bool.
cout << (2||6) << endl;
prints 1 because it is true. Try this to see the difference: cout << boolalpha << 7 << ", " << (2||6) << endl;
cout << 2 || 6 << endl;
will fail to compile on conformant implementations, because the << operator has higher precedence than the || operator, and operator << (bool, smanip) is not defined in the standard. If you only use: cout << 2 || 6;
then you can trick yourself, but the precedence rules actually group it as: (cout << 2) || 6;
Hence, the logical operation (which produces a boolean value) happens after the output operation...
While C lacks a strict bool data type, it implements all the machinery for one. Hence, the output will still be a "1" or a "0".
Yes, I'm aware of that. I was pointing out that whatever compiler codepad.org uses, it outputs the word "true" instead of 1.
will fail to compile on conformant implementations, because the << operator has higher precedence than the || operator ... Hence, the logical operation (which produces a boolean value) happens after the output operation...