An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulation. An expression is a combination of variables, constants, and operators that evaluates to a single value.
1. Arithmetic Operators
These are used for standard mathematical calculations.
| Operator | Name | Example | Result |
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 8 - 2 | 6 |
* | Multiplication | 4 * 2 | 8 |
/ | Division | 10 / 3 | 3 (Integer Division) |
% | Modulo (Remainder) | 10 % 3 | 1 |
++ | Increment (add 1) | x++ | x becomes x + 1 |
-- | Decrement (subtract 1) | x-- | x becomes x - 1 |
Note on Increment/Decrement:
++x(prefix) increments the value before the expression is evaluated.x++(postfix) increments the value after the expression is evaluated.
2. Assignment Operators
These are used to assign a value to a variable. The simple assignment operator is =. The compound assignment operators provide a shorthand for performing an arithmetic operation and an assignment simultaneously.
| Operator | Example | Equivalent To |
= | a = 5 | Assigns 5 to a |
+= | a += 3 | a = a + 3 |
*= | a *= 2 | a = a * 2 |
/= | a /= 4 | a = a / 4 |
%= | a %= 5 | a = a % 5 |
3. Relational (Comparison) Operators
These operators are used to compare two values and always return a result that is interpreted as true (non-zero value, usually 1) or false (zero value, 0).
| Operator | Name | Example |
== | Equal to | a == b |
!= | Not equal to | a != b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater than or equal to | a >= b |
<= | Less than or equal to | a <= b |
4. Logical Operators
These operators combine the results of two or more relational expressions. They are fundamental for creating complex conditions in control flow structures (like if statements).
| Operator | Name | Description |
&& | Logical AND | Returns true (1) only if both operands are true. |
| **` | `** | |
! | Logical NOT | Reverses the logical state of its operand (true becomes false, false becomes true). |
Example of Logical Expression:
// Check if age is between 18 and 65
if (age >= 18 && age <= 65) {
// ...
}
5. Operator Precedence and Associativity
When an expression contains multiple operators, the precedence determines the order in which they are evaluated. Operators with higher precedence are evaluated first.
*,/, and%have higher precedence than+and-.- Parentheses
()can always be used to override the default precedence.
Associativity determines the order when two operators have the same precedence (e.g., left-to-right).
Example:
In the expression 2 + 3 * 4, multiplication (*) is performed first due to higher precedence, resulting in $2 + 12 = 14$.
If we use parentheses:
// Result: 14 (3 * 4 is done first)
int result1 = 2 + 3 * 4;
// Result: 20 (2 + 3 is done first)
int result2 = (2 + 3) * 4;
