Operator Precedence
The following tables show the order in which operators are evaluated. Please
note the following.
-
The order in which the operands are evaluated is not specified in the ANSII
standard.
-
For readability you should not rely on these rules! Put everything in brackets
so you intension is clear to the compiler and other programmers.
-
It is important to note that there is no specified precedence for the operation
of changing a variable into a value. For example, consider the following
code:
float x, result;
x = 1;
result = x / ++x;
The value of result is not guaranteed to be consistent across different
compilers, because it is not clear whether the computer should change the
variable x before using it. The bottom line is that you should not use the
same variable multiple times in a single expression when using operators
with side effects.
-
o
Summary table.
-
o
Table in detail.
-
o
Operators listed by type.
All operators on the same line have the same precedence. The first line has
the highest precedence.
()
[]
->
.
!
~
++
--
+
-
*
&
sizeof
*
/
%
+
-
<<
>>
<
<=
>=
>
==
!=
&
^
|
&&
||
?:
=
+=
-=
*=
/=
%=
&=
^=
|=
<<=
>>=
,
Lary Huang has told me that the postfix unary -- and
postfix unary ++ have a higher precedence than the
prefix unary -- and prefix unary ++.
Detailed precedence table.
All operators in the same 'block' have the same precedence. The first block
has the highest precedence.
Group
Operator
Description
Example
Membership.
[]
Array
value = array[5] + increment;
::
Scoping
Class::age = 2;
Unary.
~
Bitwise complement
flags = ~flags;
+
Unary plus
int i = +1;
-
Unary Minus
int i = -1;
sizeof
size in bytes
int size = sizeof(floatNum);
selector
->*
Member pointer selector
ptr->*var = 24;
.*
Member pointer selector
obj.*var = 24;
Binary.
*
Multiply.
int i = 2 * 4;
/
Divide.
float f = 10 / 3;
Binary term
+
Addition
int i = 2 + 3;
-
Subtraction.
int i = 5 - 1;
Bitwise Shift
Relational.
<
Less than.
if( i < 42 ) ...
>
Greater than.
if( i > 42 ) ...
<=
Less than or equal too.
if( i <= 42 ) ...
>=
Greater than or equal too.
if( i >= 42 ) ...
Equality
==
Equal too.
if( i == 42 ) ...
!=
Not equal too.
if( i != 42 ) ...
Bitwise AND
Bitwise XOR
Bitwise OR
Logical.
Logical.
Conditional
Assignment
Series
,
Comma
for( i = 0, j = 0; i < 10; i++, j++ ) ...
See also:
o
Expressions and operators.
o
Assignment Operators.
Martin Leslie