CIS 150 - Operators and operator precedence

Objectives

  • Use operators in expressions
  • Create correct expressions using operator precedence

Table of operators

The operators in the table below are listed in descending order of precedence. The highlighted operators are the operators that we will use in this course. Just as in algebra, parentheses can be used to change the order of precedence.

Level    OperatorDescriptionAssociativity
0::scope resolutionLeft to Right
1++post-incrementLeft to Right
--post-decrement
()function call
[]array subscripting
.member selection via reference
->member selection via pointer
typeid()run-time type info
const_casttype cast
dynamic_casttype cast
reinterpret_casttype cast
static_casttype cast
2++pre-incrementRight to Left
--pre-decrement
+unary plus
-unary minus
!logical NOT
~bitwise NOT
(type)type cast
*dereference
&address-of
sizeofsize-of
newdynamic memory allocation
new[]dynamic array memory allocation
deletedynamic memory deallocation
delete[]dynamic array memory deallocation
3.*pointer to member using referenceLeft to Right
->*pointer to member using pointer
4*multiplicationLeft to Right
/division
%modulus (remainder)
5+additionLeft to Right
-subtraction
6<<bitwise left shiftLeft to Right
>>bitwise right shift
7<relational: less thanLeft to Right
<=relational: less than or equal
>relational: greater than
>=relational: greater than or equal
8==relational: equalLeft to Right
!=relational: not equal
9&bitwise ANDLeft to Right
10^bitwise XORLeft to Right
11|bitwise ORLeft to Right
12&&logical ANDLeft to Right
13||logical ORLeft to Right
14c?t:fconditional (ternary)Right to Left
15=assignmentRight to Left
+=addition and assignment
-=subtraction and assignment
*=multiplication and assignment
/=division and assignment
%=remainder and assignment
<<=bitwise left shift and assignment
>>=bitwise right shift and assignment
&=bitwise AND and assignment
^=bitwise XOR and assignment
|=bitwise OR and assignment
16throwthrow an exceptionN/A
17,list separatorLeft to Right

Operator synonyms

C++ also includes keywords as synonyms for some operators. They are as follows:

keyword     synonym for
and&&
and_eq&=
bitand&
bitor|
compl~
not!
not_eq!=
or||
or_eq|=
xor^
xor_eq^=

Examples

  • Add n1 and n2 and store the result in n3: n3 = n1 + n2
  • This will end up adding 3, 12, and 3: 3 + 2 * 6 + 3
  • This will end up multiplying 5 and 9: (3 + 2) * (6 + 3)
  • If n is set to 9, then n++ will set it to 10
  • If n is set to 9, then n+=4 will set it to 13
  • If flag is set to true, then !flag is false
  • If n is set to 7, then n % 4 is 3 (the remainder after dividing by 4)
  • If n is set to 52, then n % 10 is 2 (the remainder after dividing by 2)
  • 48 / 10 is equal to 4 (integer division truncates the result)
  • 48 / 10.0 is equal to 4.8 (the 48 was converted to a double to match the data type of 10.0, so not integer division)

Additional resource

See also: http://www.cplusplus.com/doc/tutorial/operators/