Skip to content

Operators

C++ provides a rich set of operators to manipulate data.

Arithmetic Operators

Standard mathematical operations.

Operator Description Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b (Integer division truncates!)
% Modulo (Remainder) a % b (Integers only)
1
2
3
4
int a = 10, b = 3;
int div = a / b; // 3
int mod = a % b; // 1
double exact = static_cast<double>(a) / b; // 3.333...

Assignment Operators

Operator Description Equivalent To
= Assign x = y
+= Add and assign x = x + y
-= Subtract and assign x = x - y
*= Multiply and assign x = x * y
/= Divide and assign x = x / y
%= Modulo and assign x = x % y

Increment and Decrement

  • Prefix (++i): Increments, then returns the new value. (Preferred for performance)
  • Postfix (i++): Returns the old value, then increments.
1
2
3
int i = 0;
int a = ++i; // i is 1, a is 1
int b = i++; // b is 1, i is 2

Relational (Comparison) Operators

Return true or false.

Operator Description
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to

Logical Operators

Used to combine boolean conditions.

Operator Description Example
&& Logical AND (a > 0) && (b < 10)
\|\| Logical OR (a == 0) \|\| (b == 0)
! Logical NOT !(is_ready)

Short-circuit evaluation: - In A && B, if A is false, B is not evaluated. - In A || B, if A is true, B is not evaluated.

Bitwise Operators

Operate on individual bits of integer types. Essential for hardware programming.

Operator Description Example (a=5 0101, b=3 0011)
& Bitwise AND a & b -> 0001 (1)
\| Bitwise OR a \| b -> 0111 (7)
^ Bitwise XOR a ^ b -> 0110 (6)
~ Bitwise NOT ~a -> 1010 (Inverted)
<< Left Shift a << 1 -> 1010 (10)
>> Right Shift a >> 1 -> 0010 (2)
// Setting a bit (e.g., bit 3)
reg |= (1 << 3);

// Clearing a bit
reg &= ~(1 << 3);

// Toggling a bit
reg ^= (1 << 3);

// Checking a bit
bool is_set = (reg & (1 << 3)) != 0;

Other Operators

  • sizeof: Returns the size in bytes. sizeof(int).
  • alignof: Returns the alignment requirement.
  • Ternary (? :): condition ? true_val : false_val.
  • Comma (,): Executes left operand, discards result, executes right operand.