Operator precedence in C++

0
45
Learn C++ free with free4dev
Learn C++ free with free4dev
This entry is part 3 of 6 in the series Learn C++

In this post, free4dev will share you topic Operator precedence in C++ programming language.

Logical && and || operators

&& has precedence over ||, this means that parentheses are placed to evaluate what would be evaluated together.

C++ uses short-circuit evaluation in && and || to not do unnecessary executions. If the left hand side of || returns true the right hand side does not need to be evaluated anymore.

Unary Operators

Unary operators act on the object upon which they are called and have high precedence.

When used postfix, the action occurs only after the entire operation is evaluated, leading to some interesting arithmetics:

Arithmetic operators

Arithmetic operators in C++ have the same precedence as they do in mathematics:

Multiplication and division have left associativity(meaning that they will be evaluated from left to right) and they have higher precedence than addition and subtraction, which also have left associativity.

We can also force the precedence of expression using parentheses ( ). Just the same way as you would do that in normal mathematics.

Logical AND and OR operators

These operators have the usual precedence in C++: AND before OR.

This code is equivalent to the following:

Adding the parenthesis does not change the behavior, though, it does make it easier to read. By adding these parentheses, no confusion exist about the intent of the writer.

You may also like:

Series NavigationPrevious: Literals in C++Next: Floating Point Arithmetic in C++

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.