C Operators
Operators are symbols that perform operations on variables and values. C has a rich set of operators divided into arithmetic, relational, logical, and bitwise categories.
1. Arithmetic Operators
Arithmetic operators perform standard mathematical operations:
- + (Addition)
- - (Subtraction)
- * (Multiplication)
- / (Division)
- % (Modulus - returns the remainder of division; only works on integers)
Integer Division vs. Float Division
Division behavior depends on the operand data types:
- Integer Division: Dividing two integers performs truncation. The decimal part is discarded.
5 / 2 evaluates to 2.
- Float Division: If at least one operand is a float or double, decimal precision is preserved.
5.0 / 2 evaluates to 2.5.
To divide integers and get a float result, use type casting:
int a = 5, b = 2;
double result = (double)a / b; // Casts 'a' to double, giving 2.5
2. Increment and Decrement Operators
Increment (++) and decrement (--) operators increase or decrease a variable's value by 1.
- Prefix (++x): Increments the variable first, then evaluates the expression.
- Postfix (x++): Evaluates the expression first with the current value, then increments the variable.
#include <stdio.h>
int main() {
int x = 5;
int y = ++x; // x becomes 6, y gets 6
int a = 5;
int b = a++; // b gets 5, a becomes 6
printf("x: %d, y: %d\n", x, y);
printf("a: %d, b: %d\n", a, b);
return 0;
}
3. Relational and Logical Operators
Relational operators compare values and evaluate to 1 (true) or 0 (false):
- == (Equal to), != (Not equal to)
- >, <, >=, <=
Logical operators combine conditions:
- && (Logical AND): True only if both conditions are true.
- || (Logical OR): True if at least one condition is true.
- ! (Logical NOT): Reverses truth value.
Short-Circuit Evaluation
Logical operators use short-circuit evaluation:
- In A && B, if A is false, B is not evaluated because the result is guaranteed to be false.
- In A || B, if A is true, B is not evaluated because the result is guaranteed to be true.
int x = 0;
if (x != 0 && (10 / x > 2)) {
// This is safe! (10 / x) is never executed because x != 0 is false,
// avoiding a division-by-zero crash.
}