C ++ Binary operators priority order

In what order are the following parameters checked (in C ++)?

if (a || b && c) { } 

I just saw this code in our application, and I hate it, I want to add some brackets just to clarify the order. But I do not want to add brackets until I find out that I am adding them to the right place.

Edit: accepted answer and next steps

This link has more information, but it is not clear what it means. It seems || and && have the same priority, in which case they are evaluated from left to right.

http://msdn.microsoft.com/en-us/library/126fe14k.aspx

+4
source share
5 answers

From here :

 a || (b && c) 

This is the default priority.

+4
source

[ http://www.cppreference.com/wiki/operator_precedence] (Found on the search query "C ++ Operator Priority")

This page tells us that & &, in group 13, has higher priority than || in group 14, so the expression is equivalent to || (b & c).

Unfortunately, the wikipedia article [ http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence] is not consistent with this, but since I have the C89 standard on my desk and this is consistent with the first site, I I'm going to revise the Wikipedia article.

+7
source

& & (boolean AND) has a higher priority than || (logical OR). Therefore, the following are identical:

 a || b && c a || (b && c) 

A good mnemonic rule is to remember that And as a multiplication, and OR - as an addition. If we replace AND with * and OR with +, we get the more familiar equivalent:

 a + b * c a + (b * c) 

Actually, in the logical logic, AND and OR act similarly to these arithmetic operators:

  aba AND ba * ba OR ba + b
 ---------------------------------------
 0 0 0 0 0 0
 0 1 0 0 1 1
 1 0 0 0 1 1
 1 1 1 1 1 1 (2 really, but we pretend it 1)
+2
source

To answer the question: it is obvious that the table in MSDN is damaged, perhaps someone is unable to make a decent HTML table (or use the Microsoft tool to create it!).
I believe this should be more like a Wikipedia table referenced by Rodrigo, where we have clear subsections.
But it is clear that the accepted answer is right, one way or another we have the same priority with && and || than with * and +, for example. The snippet you gave is clear and unambiguous for me, but I believe that adding parentheses will not hurt.

0
source

I'm not sure, but it should be easy for you to find out.

Just create a small program with an expression that displays the value of true: (true || false & true)

If the result is correct, then || has a higher priority than & &, if it is a phase, it is the other way around.

-2
source

Source: https://habr.com/ru/post/1277011/


All Articles