Priorities & Calculations in C++
C++ has a set of operator precedence rules that determine the order in which expressions are evaluated. Operators with higher precedence are evaluated before operators with lower precedence.
Here is a table of the operator precedence rules in C++:
Operator Group | Operators |
---|---|
Parentheses | () , [] , {} |
Unary operators | + , - , ! , ~ , * , & , ++ , -- , sizeof , cast , type-name |
Multiplication, division, and modulus | * , / , % |
Addition and subtraction | + , - |
Bitwise AND | & |
Bitwise OR | | |
Bitwise XOR | ^ |
Equality and inequality | == , != |
Less than, less than or equal to, greater than, greater than or equal to | < , <= , > , >= |
Logical AND | && |
Logical OR | || |
Assignment | = , += , -= , *= , /= , %= , &= , ` |
Conditional operator | ? : |
Comma | , |
When evaluating an expression, operators with the highest precedence are evaluated first, followed by operators with lower precedence.
Here are some examples of how operator precedence works in C++:
// Evaluates to 13. int x = 5 * 2 + 3; // Evaluates to 11. int y = 5 + 2 * 3; // Evaluates to true. bool z = 5 < 10 && 10 > 5; // Evaluates to false. bool w = 5 > 10 || 10 < 5;
It is important to be aware of operator precedence when writing C++ code. Otherwise, you may get unexpected results.
Here is another example of how operator precedence can be used to control the order of evaluation:
// Evaluates to 16. int a = (5 + 3) * 2; // Evaluates to 11. int b = 5 + (3 * 2);
In the first expression, the addition operator (+
) has higher precedence than the multiplication operator (*
). Therefore, the addition operation is evaluated first, and then the multiplication operation is evaluated.
In the second expression, the multiplication operation has higher precedence than the addition operation. Therefore, the multiplication operation is evaluated first, and then the addition operation is evaluated.
By understanding operator precedence, you can write more concise and efficient C++ code.