Operator Precedence in C++
C++ Operators – Part 9
Forward: In this article we look at operator precedence in C++.
By: Chrysanthus Date Published: 24 Aug 2012
Introduction
Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.
Example
Consider the following statement:
int x = 2 + 8 % 5;
There are three operators here, which are =, + and %. Now = is of a very low precedence and it is executed last. The question then is between + and %; which is executed first? If the modulus operator, % is executed first, the answer will be 5. If the Addition operator is executed first, the answer will be 0. Well, in C++, % is of a higher precedence than +, so % is executed first and the answer is 5. You can force the + to be executed first by using brackets, as follows:
int x = (2 + 8) % 5;
Whenever you are in doubts of which operator would be executed first, use brackets, to be sure that an operator would be executed first. Brackets can be nested.
Precedence Order
Scope Operator
::
Grouping (direction of operation): Left-to-right
Postfix Operators
() [] . -> ++ -- dynamic_cast static_cast reinterpret_cast const_cast typeid
Grouping: Left-to-right
Unary Prefix Operators
++ -- ~ ! sizeof new delete
Grouping: Right-to-left
Reference and Indirection Operators
& *
Grouping: Right-to-left
Unary Sign Operators
+ -
Grouping: Right-to-left
Type Casting Operators
(type)
Grouping: Right-to-left
Pointer-to-member Operators
.* ->*
Grouping: Left-to-right
Multiplicative Operators
% * /
Grouping: Left-to-right
Additive Operators
+ -
Grouping: Left-to-right
Bitwise Shift Operators
<< >>
Grouping: Left-to-right
Relational Operators
< > <= >=
Grouping: Left-to-right
Equality Operators
== !=
Grouping: Left-to-right
Bitwise AND Operator
&
Grouping: Left-to-right
Bitwise XOR Operator
^
Grouping: Left-to-right
Bitwise OR Operator
|
Grouping: Left-to-right
Logical AND Operator
&&
Grouping: Left-to-right
Logical OR Operator
||
Grouping: Left-to-right
Conditional Operator
?:
Grouping: Right-to-left
Assignment Operators
= *= /= %= += -= >>= <<= &= ^= !=
Grouping: Right-to-left
Comma Operator
,
Grouping: Left-to-right
Well, we have seen a lot in this series. We should really take a break here. We continue in the next part.
Chrys
Related Courses
C++ CourseRelational Database and Sybase
Windows User Interface
Computer Programmer – A Jack of all Trade – Poem