Chapter 7: Operators and Expressions
Operators are the verbs of the C language. They allow you to manipulate data at the bit and byte level. Understanding operator precedence and associativity is crucial to avoiding subtle bugs.
I. Arithmetic and Relational Operators
| Type | Operators | Examples |
|---|---|---|
| Arithmetic | +, -, *, /, % | 10 % 3 = 1 |
| Relational | ==, !=, >, <, >=, <= | 5 == 5 is 1 (true) |
| Logical | &&, ` |
Integer Division Warning
In C, if both operands of / are integers, the result is an integer (truncated). To get a float result, at least one operand must be a float.
int x = 5 / 2; // result: 2
float y = 5.0 / 2; // result: 2.5
II. Bitwise Operators
C's primary strength for system programming is its ability to manipulate individual bits directly.
| Operator | Action | Purpose |
|---|---|---|
& | Bitwise AND | Masking bits |
| ` | ` | Bitwise OR |
^ | Bitwise XOR | Toggling bits |
~ | Bitwise NOT | One's complement |
<< | Left Shift | Multiply by power of 2 |
>> | Right Shift | Divide by power of 2 |
// Setting a specific bit (Bit 3)
unsigned char reg = 0x00;
reg |= (1 << 3); // reg is now 0x08
III. Increment and Decrement
- Prefix (
++x): Increments the value and then uses it in the expression. - Postfix (
x++): Uses the current value in the expression and then increments it.
int a = 5, b;
b = a++; // b is 5, a becomes 6
b = ++a; // a becomes 7, b is 7
IV. Precedence and Associativity
Operators are not evaluated simply left-to-right. They follow a hierarchy.
Mnemonic: Always use parentheses () when you are unsure about precedence. It makes the code more readable and prevents logical errors.
V. Ternary Operator
The only three-operand operator in C. It is a shorthand for an if-else statement.
// condition ? value_if_true : value_if_false
int max = (a > b) ? a : b;
VI. Compound Assignment
Shortcuts like +=, *=, &= perform the operation and the assignment in a single step.
x += 5; // same as x = x + 5