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
.
Since C++ doesn't really care about whitespace, the same thing would
be true if you had written:
int result = 4+5 * 6+2;
The result would still be
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 in C++
Operator precedence in C++ is incredibly easy! Don't let anyone tell
you otherwise! Here's the trick: if you don't know the order of
precedence, or you're not sure, add parentheses! Don't even bother
looking it up. We can guarantee that it will be faster for you to add
parentheses than to look it up in this tutorial or in a C++ book.
Adding parentheses has another obvious benefit - it makes your code
much easier to read. Chances are, if you are uncertain about
the order of precedence, anyone reading your code will have the same
uncertainty.
That having been said, here's the order of operator precedence. In
general, the order is what you would think it is - that is, you can
safely say
int x = 4 + 3;
and it will correctly add
4
and
3
before
assigning to
x
. Our advice is to read this table once
and then never refer to it again.
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 |
|
* | 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 |
Related Posts : C++
No comments:
Post a Comment