Skip to content

C++ Operators

An operator is a symbol that instructs the compiler to perform specific mathematical, logical, or manipulative operations. C++ offers a rich set of built-in operators, categorized as:

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Miscellaneous Operators (including ternary conditional, sizeof, cast, pointer, etc.)

This chapter explores these operators.

These perform standard mathematical calculations.

Assume int a = 10; and int b = 20;

OperatorNameDescriptionExample
+AdditionAdds two operandsa + b // result is 30
-SubtractionSubtracts the second operand from the firstb - a // result is 10
*MultiplicationMultiplies both operandsa * b // result is 200
/DivisionDivides the first operand by the second. Result is integer if both operands are integers.b / a // result is 2
%ModulusComputes the remainder of integer divisionb % a // result is 0
++IncrementIncreases integer value by one. Pre-increment (++a) increments before use, Post-increment (a++) increments after use.++a // a becomes 11, result is 11
a++ // a becomes 11, result is 10 (original value)
—DecrementDecreases integer value by one. Pre/Post behavior similar to increment.—a // a becomes 9, result is 9
a— // a becomes 9, result is 10 (original value)

These compare two operands and return a boolean result (true or false).

Assume int a = 10; and int b = 20;

OperatorNameDescriptionExample
==Equal toChecks if the values of two operands are equal.(a == b) // false
!=Not equal toChecks if the values of two operands are not equal.(a != b) // true
>Greater thanChecks if the value of the left operand is greater than the right.(a > b) // false
<Less thanChecks if the value of the left operand is less than the right.(a < b) // true
>=Greater than or equal toChecks if the left operand is greater than or equal to the right.(a >= b) // false
<=Less than or equal toChecks if the left operand is less than or equal to the right.(a <= b) // true

Note: C++20 introduced the three-way comparison operator (<=>), also known as the spaceship operator, which can simplify comparison logic, but these fundamental operators remain essential.

These operate on boolean operands and are typically used to combine relational expressions.

Assume bool condition1 = true; and bool condition2 = false;

OperatorNameDescriptionExample
&&Logical ANDResult is true only if both operands are true. Uses short-circuit evaluation (if the first operand is false, the second is not evaluated).(condition1 && condition2) // false
||Logical ORResult is true if at least one operand is true. Uses short-circuit evaluation (if the first operand is true, the second is not evaluated).(condition1 || condition2) // true
!Logical NOTReverses the logical state of its operand. true becomes false, false becomes true.!condition1 // false
!condition2 // true

These operate directly on the binary (bit) representation of integer operands.

Truth table for basic bitwise operations:

pqp & q (AND)p | q (OR)p ^ q (XOR)
00000
01011
11110
10011

Assume unsigned int a = 60; (binary 0011 1100) and unsigned int b = 13; (binary 0000 1101). Using unsigned int avoids sign extension complexities for this example.

a = 0011 1100
b = 0000 1101
-----------------
a & b = 0000 1100 (Decimal 12)
a | b = 0011 1101 (Decimal 61)
a ^ b = 0011 0001 (Decimal 49)
~a = 1100 0011 (Depends on int size and signedness; for unsigned 8-bit: 195. For signed 8-bit using 2's complement, it might represent -61)
OperatorNameDescriptionExample (using a=60, b=13)
&Bitwise ANDCopies a bit to the result if it exists in both operands.(a & b) // result is 12 (0000 1100)
|Bitwise ORCopies a bit if it exists in either operand.(a | b) // result is 61 (0011 1101)
^Bitwise XORCopies the bit if it is set in one operand but not both.(a ^ b) // result is 49 (0011 0001)
~Bitwise ComplementUnary operator; flips all the bits of its operand.(~a) // result depends on integer size and signedness. For 32-bit unsigned int, it’s a large positive number. For signed int, typically results in -(a+1) due to two’s complement.
<<Left ShiftShifts the bits of the left operand to the left by the number of positions specified by the right operand. Fills vacated bits with zeros.a << 2 // result is 240 (1111 0000)
>>Right ShiftShifts the bits of the left operand to the right. Behavior for signed types is implementation-defined for the vacated leftmost bits (usually sign bit replication - arithmetic shift), while unsigned types fill with zeros (logical shift).a >> 2 // result is 15 (0000 1111)

These assign values to variables. The compound assignment operators provide shorthand for common operations.

Assume int c = 0; int a = 10; int b = 20;

OperatorNameDescriptionExample
=Simple AssignmentAssigns the value of the right operand to the left operand.c = a + b; // c becomes 30
+=Add and AssignAdds the right operand to the left operand and assigns the result to the left.c += a; // equivalent to c = c + a;
-=Subtract and AssignSubtracts the right operand from the left and assigns the result to the left.c -= a; // equivalent to c = c - a;
*=Multiply and AssignMultiplies the left operand by the right and assigns the result to the left.c *= a; // equivalent to c = c * a;
/=Divide and AssignDivides the left operand by the right and assigns the result to the left.c /= a; // equivalent to c = c / a;
%=Modulus and AssignComputes modulus using both operands and assigns the result to the left.c %= a; // equivalent to c = c % a;
<<=Left Shift and AssignPerforms bitwise left shift and assigns.c <<= 2; // equivalent to c = c << 2;
>>=Right Shift and AssignPerforms bitwise right shift and assigns.c >>= 2; // equivalent to c = c >> 2;
&=Bitwise AND and AssignPerforms bitwise AND and assigns.c &= a; // equivalent to c = c & a;
^=Bitwise XOR and AssignPerforms bitwise XOR and assigns.c ^= a; // equivalent to c = c ^ a;
|=Bitwise OR and AssignPerforms bitwise OR and assigns.c |= a; // equivalent to c = c | a;

Other important operators in C++:

OperatorNameDescriptionExample
sizeofSizeof OperatorReturns the size (in bytes) of a data type or a variable. The result type is size_t. Size can vary by platform/compiler.sizeof(int) // returns size of int (e.g., 4)
sizeof(myVariable) // returns size of myVariable
?:Ternary Conditional OperatorSyntax: Condition ? ValueIfTrue : ValueIfFalse. Evaluates the condition. If true, it returns ValueIfTrue; otherwise, it returns ValueIfFalse.int maxVal = (a > b) ? a : b;
,Comma OperatorEvaluates several expressions sequentially, from left to right. The result of the whole expression is the value of the rightmost expression. Often used in for loops.x = (a++, b++); // increments a, then increments b, then assigns the original value of b to x
. (dot) and -> (arrow)Member Access Operators. is used to access members (variables or functions) of an object. -> is used to access members via a pointer to an object.myObject.member
myPointer->member (equivalent to (*myPointer).member)
Casting OperatorsType CastingConvert a value from one data type to another. Modern C++ prefers explicit casts: static_cast, dynamic_cast, const_cast, reinterpret_cast. Avoid C-style casts ((type)value or type(value)).int i = static_cast<int>(2.718); // i becomes 2
float f = static_cast<float>(i);
&Address-of OperatorUnary operator; returns the memory address of its operand.int* ptr = &myVariable; // ptr stores the address of myVariable
*Dereference OperatorUnary operator; accesses the value stored at the memory address held by a pointer.int value = *ptr; // value gets the content pointed to by ptr

Operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated before operators with lower precedence. Associativity defines the order for operators with the same precedence (left-to-right or right-to-left).

For example, in x = 7 + 3 * 2;, multiplication (*) has higher precedence than addition (+), so 3 * 2 is evaluated first (result 6), then 7 + 6 (result 13). x becomes 13.

Use parentheses () to override precedence or improve clarity: x = (7 + 3) * 2; results in x being 20.

Here is a summary of C++ operator precedence (highest to lowest) and associativity:

CategoryOperatorAssociativity
Scope Resolution::Left-to-right
Postfix/Primary() [] . -> ++ -- typeid static_cast dynamic_cast const_cast reinterpret_castLeft-to-right
Unary/Prefix+ - ! ~ ++ -- * & sizeof new delete (type) noexcept alignofRight-to-left
Member Pointer Access.* ->*Left-to-right
Multiplicative* / %Left-to-right
Additive+ -Left-to-right
Shift<< >>Left-to-right
Three-way comparison (C++20)<=>Left-to-right
Relational< <= > >=Left-to-right
Equality== !=Left-to-right
Bitwise AND&Left-to-right
Bitwise XOR^Left-to-right
Bitwise OR|Left-to-right
Logical AND&&Left-to-right
Logical OR||Left-to-right
Conditional (Ternary)?:Right-to-left
Assignment= += -= *= /= %= <<= >>= &= ^= |=Right-to-left
Throw expressionthrowRight-to-left
Comma,Left-to-right

Refer to authoritative sources like cppreference.com for the definitive precedence table. When in doubt, use parentheses!