0
Which had higher precedence == or || operator?
7 Respostas
+ 9
You can easily google the operator precedence table for C++.
You can check it here : http://en.cppreference.com/w/cpp/language/operator_precedence
+ 1
To find it out if == has lower precedence than a logical OR, run this short snippet:
if (0 == 2 || 1)
std::cout << "Bjarne\n";
else
std::cout << "Stroustrup\n";
If the learbook is right it should print "Stroustrup". And if it's wrong... maybe you should get another book!
+ 1
Damyian G your example is wrong. Regardless of the precedence of == it will always return true. To prove it I forced the precedence below.
if (1 || (2 == 0))
std::cout << "Bjarne\n";
else
std::cout << "Stroustrup\n";
It will always output Bjarne.
This is due to the way || short circuits.
Even if the code to the right is ran first it isn't evaluated as far as the logical or is considered. It would then jump back to the left of or and since it has a value of 1, which is equal to true, it jumps out of the condition and never checks the right side of the logical or.
+ 1
if (1 == 0 || 0 == 0)
cout << "Bjarne\n";
else
cout << "Stroustrup\n";
This might be a better example (I'm sure there are much better ones out there) that shows that == has higher precedence than ||
edited: had a 1 where 0 was needed. should be correct now.
+ 1
@ChaoticDawg - You are right, thanks for the correction. I had the order of my conditions in reverse.
Updated my answer.
0
I have a learbook, there is written == has lower precedence than ||, is that true?
0
There shall be grammatical error. I can prove it.