Operator Precedence

 

So far, we've seen a number of different operators. Here's a summary of the operators we've covered so far:

 

Boolean operators

&&, ||, !

Arithmetic operators

+, -, *, /, %

Equality operators

<, >, ==, <=, >=, !=

Assignment operators

=, +=, -=, *=, /=, %=

What is operator precedence?

Operator precedence refers to the order in which operators get used. An operator with high precedence will get used before an operator with lower precedence. Here's an example:

  int result = 4 + 5 * 6 + 2;

What will be the value of result? The answer depends on the precedence of the operators. In C++, the multiplication operator (*) has higher precedence than the addition operator (+). What that means is, the multiplication 5 * 6 will take place before either of the additions, so your expression will resolve to 4 + 30 + 2 , so result will store the value 36.

Maybe you wanted to take the sum 4 + 5 and multiply it by the sum 6 + 2 for a result of 72? Just as in math class, add parentheses. You can write:

  int result = (4 + 5) * (6 + 2);

Operator precedence

operators have the same precedence as other operators in their group, and higher precedence than operators in lower groups

operator

name

!

boolean not


++ , -- , + ,-(negation)

 

*

multiplication

/

division

%

mod


+

addition

-

subtraction


<

is less than

<=

is less than or equal to

>

is greater than

>=

is greater than or equal to


==

is equal to

!=

is not equal to


&&

boolean and


||

boolean or


=

assignment

*=

multiply and assign

/=

divide and assign

%=

mod and assign

+=

add and assign

-=

subtract and assign