C++ Operators
Operators in C++
Section titled “Operators in C++”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.
Arithmetic Operators
Section titled “Arithmetic Operators”These perform standard mathematical calculations.
Assume int a = 10; and int b = 20;
| Operator | Name | Description | Example |
|---|---|---|---|
| + | Addition | Adds two operands | a + b // result is 30 |
| - | Subtraction | Subtracts the second operand from the first | b - a // result is 10 |
| * | Multiplication | Multiplies both operands | a * b // result is 200 |
| / | Division | Divides the first operand by the second. Result is integer if both operands are integers. | b / a // result is 2 |
| % | Modulus | Computes the remainder of integer division | b % a // result is 0 |
| ++ | Increment | Increases 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) |
| — | Decrement | Decreases 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) |
Relational Operators
Section titled “Relational Operators”These compare two operands and return a boolean result (true or false).
Assume int a = 10; and int b = 20;
| Operator | Name | Description | Example |
|---|---|---|---|
| == | Equal to | Checks if the values of two operands are equal. | (a == b) // false |
| != | Not equal to | Checks if the values of two operands are not equal. | (a != b) // true |
| > | Greater than | Checks if the value of the left operand is greater than the right. | (a > b) // false |
| < | Less than | Checks if the value of the left operand is less than the right. | (a < b) // true |
| >= | Greater than or equal to | Checks if the left operand is greater than or equal to the right. | (a >= b) // false |
| <= | Less than or equal to | Checks 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.
Logical Operators
Section titled “Logical Operators”These operate on boolean operands and are typically used to combine relational expressions.
Assume bool condition1 = true; and bool condition2 = false;
| Operator | Name | Description | Example |
|---|---|---|---|
| && | Logical AND | Result 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 OR | Result 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 NOT | Reverses the logical state of its operand. true becomes false, false becomes true. | !condition1 // false !condition2 // true |
Bitwise Operators
Section titled “Bitwise Operators”These operate directly on the binary (bit) representation of integer operands.
Truth table for basic bitwise operations:
| p | q | p & q (AND) | p | q (OR) | p ^ q (XOR) |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 0 |
| 1 | 0 | 0 | 1 | 1 |
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 1100b = 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)| Operator | Name | Description | Example (using a=60, b=13) |
|---|---|---|---|
| & | Bitwise AND | Copies a bit to the result if it exists in both operands. | (a & b) // result is 12 (0000 1100) |
| | | Bitwise OR | Copies a bit if it exists in either operand. | (a | b) // result is 61 (0011 1101) |
| ^ | Bitwise XOR | Copies the bit if it is set in one operand but not both. | (a ^ b) // result is 49 (0011 0001) |
| ~ | Bitwise Complement | Unary 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 Shift | Shifts 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 Shift | Shifts 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) |
Assignment Operators
Section titled “Assignment Operators”These assign values to variables. The compound assignment operators provide shorthand for common operations.
Assume int c = 0; int a = 10; int b = 20;
| Operator | Name | Description | Example |
|---|---|---|---|
| = | Simple Assignment | Assigns the value of the right operand to the left operand. | c = a + b; // c becomes 30 |
| += | Add and Assign | Adds the right operand to the left operand and assigns the result to the left. | c += a; // equivalent to c = c + a; |
| -= | Subtract and Assign | Subtracts the right operand from the left and assigns the result to the left. | c -= a; // equivalent to c = c - a; |
| *= | Multiply and Assign | Multiplies the left operand by the right and assigns the result to the left. | c *= a; // equivalent to c = c * a; |
| /= | Divide and Assign | Divides the left operand by the right and assigns the result to the left. | c /= a; // equivalent to c = c / a; |
| %= | Modulus and Assign | Computes modulus using both operands and assigns the result to the left. | c %= a; // equivalent to c = c % a; |
| <<= | Left Shift and Assign | Performs bitwise left shift and assigns. | c <<= 2; // equivalent to c = c << 2; |
| >>= | Right Shift and Assign | Performs bitwise right shift and assigns. | c >>= 2; // equivalent to c = c >> 2; |
| &= | Bitwise AND and Assign | Performs bitwise AND and assigns. | c &= a; // equivalent to c = c & a; |
| ^= | Bitwise XOR and Assign | Performs bitwise XOR and assigns. | c ^= a; // equivalent to c = c ^ a; |
| |= | Bitwise OR and Assign | Performs bitwise OR and assigns. | c |= a; // equivalent to c = c | a; |
Miscellaneous Operators
Section titled “Miscellaneous Operators”Other important operators in C++:
| Operator | Name | Description | Example |
|---|---|---|---|
sizeof | Sizeof Operator | Returns 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 Operator | Syntax: Condition ? ValueIfTrue : ValueIfFalse. Evaluates the condition. If true, it returns ValueIfTrue; otherwise, it returns ValueIfFalse. | int maxVal = (a > b) ? a : b; |
, | Comma Operator | Evaluates 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.membermyPointer->member (equivalent to (*myPointer).member) |
| Casting Operators | Type Casting | Convert 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 2float f = static_cast<float>(i); |
& | Address-of Operator | Unary operator; returns the memory address of its operand. | int* ptr = &myVariable; // ptr stores the address of myVariable |
* | Dereference Operator | Unary operator; accesses the value stored at the memory address held by a pointer. | int value = *ptr; // value gets the content pointed to by ptr |
Operators Precedence in C++
Section titled “Operators Precedence in C++”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:
| Category | Operator | Associativity |
|---|---|---|
| Scope Resolution | :: | Left-to-right |
| Postfix/Primary | () [] . -> ++ -- typeid static_cast dynamic_cast const_cast reinterpret_cast | Left-to-right |
| Unary/Prefix | + - ! ~ ++ -- * & sizeof new delete (type) noexcept alignof | Right-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 expression | throw | Right-to-left |
| Comma | , | Left-to-right |
Refer to authoritative sources like cppreference.com for the definitive precedence table. When in doubt, use parentheses!