C: Operators: Arithmetic & Precedence
Operators are like kitchen tools — a chef's knife for chopping, a peeler for skins, scissors for packaging. Different ingredients need different tools, and different calculations need different operators. Learn what each one is for and where it breaks down, and your expressions will stop surprising you.
TL;DR: C operators fall into five groups: arithmetic (
+ - * / %), relational (== != < > <= >=), logical (&& || !), assignment (=plus+=and friends), and others (?:,,,sizeof). The two classic traps are integer division dropping decimals and writing=where you meant==. When unsure about precedence, add parentheses.
1. Arithmetic Operators
C provides 7 basic arithmetic operators for the most common mathematical calculations.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 5 - 3 |
2 |
* |
Multiplication | 5 * 3 |
15 |
/ |
Division | 7 / 2 |
3 |
% |
Modulo | 7 % 2 |
1 |
+ |
Unary plus | +5 |
5 |
- |
Unary minus | -5 |
-5 |
(1) The Integer Division Trap
When two integers are divided, the result is also an integer — the fractional part is simply discarded, not rounded.
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int a = 7;
// Variable declaration
int b = 2;
// I/O operation
printf("%d / %d = %d\n", a, b, a / b);
// I/O operation
printf("%d %% %d = %d\n", a, b, a % b);
// Return result
return 0;
}
7 / 2 = 3
7 % 2 = 1
7.0 / 2 gives 3.5.
(2) Uses of the Modulo Operator
The modulo operator % only works with integers. It has several very practical use cases:
- Checking even/odd:
n % 2equals 0 means even - Getting the last digit:
n % 10gives the ones place - Circular indexing:
i % sizekeeps the index cycling between 0 and size-1
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int n = 12345;
// I/O operation
printf("Last digit: %d\n", n % 10);
// I/O operation
printf("Is even: %s\n", n % 2 == 0 ? "Yes" : "No");
// Return result
return 0;
}
Last digit: 5
Is even: No
2. Increment and Decrement Operators
The increment operator ++ adds 1 to a variable, and -- subtracts 1. Each comes in two forms: prefix and postfix, which differ in what the expression returns.
(1) Prefix vs. Postfix
| Form | Name | Effect | Expression Value |
|---|---|---|---|
++i |
Prefix increment | i increases by 1 | The new (increased) value |
i++ |
Postfix increment | i increases by 1 | The old (original) value |
--i |
Prefix decrement | i decreases by 1 | The new (decreased) value |
i-- |
Postfix decrement | i decreases by 1 | The old (original) value |
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int a = 5;
// Variable declaration
int b = ++a;
// I/O operation
printf("Prefix: a=%d, b=%d\n", a, b);
// Variable declaration
int c = 5;
// Variable declaration
int d = c++;
// I/O operation
printf("Postfix: c=%d, d=%d\n", c, d);
// Return result
return 0;
}
Prefix: a=6, b=6
Postfix: c=6, d=5
a = ++a + a++. The behavior is undefined, and different compilers will give different results.
3. Relational Operators
Relational operators compare two values, returning "true" (1) or "false" (0).
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
Equal to | 5 == 5 |
1 |
!= |
Not equal to | 5 != 3 |
1 |
< |
Less than | 3 < 5 |
1 |
> |
Greater than | 3 > 5 |
0 |
<= |
Less than or equal | 5 <= 5 |
1 |
>= |
Greater than or equal | 3 >= 5 |
0 |
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int a = 10;
// Variable declaration
int b = 20;
// I/O operation
printf("a == b: %d\n", a == b);
// I/O operation
printf("a != b: %d\n", a != b);
// I/O operation
printf("a < b: %d\n", a < b);
// Return result
return 0;
}
a == b: 0
a != b: 1
a < b: 1
== is comparison, = is assignment. Mixing them up turns the comparison into an assignment that won't produce an error. A good habit is to put the constant on the left: 5 == a — if you accidentally write 5 = a, the compiler will catch it.
4. Logical Operators
Logical operators combine multiple conditions, also returning 1 (true) or 0 (false).
| Operator | Meaning | Example | Result |
|---|---|---|---|
&& |
Logical AND | 1 && 0 |
0 |
| ` | ` | Logical OR | |
! |
Logical NOT | !0 |
1 |
(1) Truth Table
| A | B | A && B | A || B | !A | |---|---|--------|--------|----| | 0 | 0 | 0 | 0 | 1 | | 0 | 1 | 0 | 1 | 1 | | 1 | 0 | 0 | 1 | 0 | | 1 | 1 | 1 | 1 | 0 |
(2) Short-Circuit Evaluation
With &&, if the left side is false, the right side is never evaluated. With ||, if the left side is true, the right side is skipped. This feature can be used to avoid illegal operations:
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int divisor = 0;
// Variable declaration
int value = 10;
// Conditional check
if (divisor != 0 && value / divisor > 5) {
// I/O operation
printf("Condition met\n");
} else {
// I/O operation
printf("Condition not met, and no division by zero\n");
}
// Return result
return 0;
}
Condition not met, and no division by zero
-5 is "true" in a logical context.
5. Assignment Operators
The basic assignment operator = stores the right-hand value into the left-hand variable. C also provides compound assignment operators that combine an operation with assignment.
| Compound | Equivalent |
|---|---|
a += b |
a = a + b |
a -= b |
a = a - b |
a *= b |
a = a * b |
a /= b |
a = a / b |
a %= b |
a = a % b |
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int score = 80;
score += 10;
// I/O operation
printf("After bonus: %d\n", score);
score -= 25;
// I/O operation
printf("After penalty: %d\n", score);
score *= 2;
// I/O operation
printf("After doubling: %d\n", score);
// Return result
return 0;
}
After bonus: 90
After penalty: 65
After doubling: 130
6. The Conditional Operator (Ternary Operator)
The conditional operator ?: is C's only ternary operator. Its syntax is:
condition ? expression1 : expression2
If the condition is true, expression1 is evaluated; otherwise, expression2 is evaluated. It's a shorthand for if-else.
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int age = 20;
// Variable declaration
char *status = age >= 18 ? "Adult" : "Minor";
// I/O operation
printf("Age %d, %s\n", age, status);
// Variable declaration
int a = 15, b = 28;
// Variable declaration
int max = a > b ? a : b;
// I/O operation
printf("Larger value: %d\n", max);
// Return result
return 0;
}
Age 20, Adult
Larger value: 28
7. The Comma Operator
The comma operator , evaluates each expression from left to right, and the value of the entire comma expression is the value of the last expression.
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int a, b, c;
c = (a = 1, b = 2, a + b);
// I/O operation
printf("a=%d, b=%d, c=%d\n", a, b, c);
// Return result
return 0;
}
a=1, b=2, c=3
8. The sizeof Operator
sizeof returns the number of bytes a data type or variable occupies in memory. It's evaluated at compile time, not runtime.
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// I/O operation
printf("char: %zu bytes\n", sizeof(char));
// I/O operation
printf("int: %zu bytes\n", sizeof(int));
// I/O operation
printf("float: %zu bytes\n", sizeof(float));
// I/O operation
printf("double: %zu bytes\n", sizeof(double));
int arr[5] = {1, 2, 3, 4, 5};
// I/O operation
printf("Array total size: %zu bytes\n", sizeof(arr));
// I/O operation
printf("Array element count: %zu\n", sizeof(arr) / sizeof(arr[0]));
// Return result
return 0;
}
char: 1 bytes
int: 4 bytes
float: 4 bytes
double: 8 bytes
Array total size: 20 bytes
Array element count: 5
sizeof requires parentheses for type names (sizeof(int)) but not for variables (sizeof a). However, for consistency, it's best to always use parentheses.
9. Operator Precedence
When an expression contains multiple operators, the one with higher precedence is evaluated first. The table below lists them from highest to lowest:
| Precedence | Operators | Associativity |
|---|---|---|
| 1 (highest) | () [] -> . |
Left to right |
| 2 | ! ~ ++ -- +(unary) -(unary) *(dereference) &(address-of) sizeof |
Right to left |
| 3 | * / % |
Left to right |
| 4 | + - |
Left to right |
| 5 | << >> |
Left to right |
| 6 | < <= > >= |
Left to right |
| 7 | == != |
Left to right |
| 8 | & |
Left to right |
| 9 | ^ |
Left to right |
| 10 | ` | ` |
| 11 | && |
Left to right |
| 12 | ` | |
| 13 | ?: |
Right to left |
| 14 | = += -= *= /= %= etc. |
Right to left |
| 15 (lowest) | , |
Left to right |
▶ Example: Precedence and Parentheses
The same expression can give different results depending on the parentheses:
▶ Try it Yourself2 + 3 * 4 = 14
(2 + 3) * 4 = 20
a + b * c = 14
(a + b) * c = 20
a > b || a < c && b < c = 1
* binds tighter than +, so 2 + 3 * 4 is 14; && binds tighter than ||, so the last line is a > b || (a < c && b < c). Add parentheses when in doubt — it guarantees correctness and readability.
▶ Example: Sum of Digits
Combine various operators to calculate the sum of each digit in a three-digit number:
▶ Try it YourselfNumber: 952
Hundreds: 9, Tens: 5, Ones: 2
Sum of digits: 16
▶ Example: Leap Year
Use logical and relational operators to determine whether a year is a leap year:
▶ Try it Yourself2024 is a leap year
10. Type Conversion
(1) Implicit Conversion
When different types are mixed in an expression, the compiler automatically converts the lower-precision type to the higher-precision type:
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int a = 5;
// Variable declaration
double b = 2.0;
// Variable declaration
double c = a / b;
// I/O operation
printf("5 / 2.0 = %f\n", c);
// Variable declaration
char ch = 'A';
// Variable declaration
int code = ch + 1;
// I/O operation
printf("'A' + 1 = %c (ASCII %d)\n", code, code);
// Return result
return 0;
}
5 / 2.0 = 2.500000
'A' + 1 = B (ASCII 66)
Conversion direction: char → int → long → double, int → unsigned → long → double.
(2) Explicit Casting
Use (type_name) to force a value to a specific type:
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int a = 7, b = 2;
// Variable declaration
double result = (double)a / b;
// I/O operation
printf("With cast: %f\n", result);
// Return result
return 0;
}
With cast: 3.500000
❓ FAQ
int values performs integer division — the fractional part is truncated, not rounded. Make at least one operand a floating-point value: 7.0 / 2 gives 3.5, or cast with (double)a / b.% be used with floating-point numbers?% only accepts integer types. For floating-point remainder use fmod() from <math.h>, e.g. fmod(7.5, 2.0) returns 1.5.a++ and ++a?++a yields the incremented value while a++ yields the old value. Never increment the same variable twice in one expression — that is undefined behavior.= and == keep getting mixed up — is there a reliable habit?if (0 == a). A typo like 0 = a then fails to compile. Compiling with -Wall also flags suspicious if (a = 0).&& skips the right side when the left is false, and || skips it when the left is true. Use it to guard division: divisor != 0 && value / divisor > 5 never divides by zero.&&, ||, assignment, comma — and add parentheses for anything else.int and double in one expression?char → int → long → double). But int / int still does integer division first, so cast to double before dividing.📖 Summary
- In arithmetic, integer division truncates the decimal part; modulo only works with integers
++/--prefix returns the new value, postfix returns the old; avoid using them multiple times on the same variable in one expression- Relational operators return 0 or 1; watch out for confusing
=with== - Logical operators
&&and||short-circuit, which can protect the right-hand expression - Don't memorize precedence — when uncertain, add parentheses
📝 Exercises
- Write a program that takes a number of seconds (e.g. 3661) and uses
/and%to calculate the corresponding hours, minutes, and seconds, then outputs the result. - Write a program that takes two integers and uses the ternary operator to find and output the larger and smaller values.
- Write a program that uses
sizeofto print the sizes ofshort,int,long, andlong longon your computer and observe the results.