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) |
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.
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) |
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.