C Operators
Operators perform actions on values, like adding, comparing or combining them.
Arithmetic Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Add | 10 + 4 | 14 |
- | Subtract | 10 - 4 | 6 |
* | Multiply | 10 * 4 | 40 |
/ | Divide | 10 / 4 | 2 |
% | Remainder | 10 % 4 | 2 |
++ | Add 1 | x++ | |
-- | Subtract 1 | x-- |
Example
c
#include <stdio.h>
int main(void) {
int minutes = 135;
int hours = minutes / 60;
int left = minutes % 60;
printf("%d hours and %d minutes\n", hours, left);
return 0;
}Output
2 hours and 15 minutes
% only works with whole numbers. A common use is checking if a number is even: n % 2 == 0.
Assignment Operators
| Operator | Same as |
|---|---|
x += 5 | x = x + 5 |
x -= 5 | x = x - 5 |
x *= 5 | x = x * 5 |
x /= 5 | x = x / 5 |
x %= 5 | x = x % 5 |
Example
c
#include <stdio.h>
int main(void) {
int stock = 50;
stock -= 12; // sold 12
stock += 30; // new delivery
stock++; // one returned
printf("Stock: %d\n", stock);
return 0;
}Output
Stock: 69
Comparison Operators
In C, a comparison gives 1 for true and 0 for false.
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> / < | Greater / less than |
>= / <= | Greater or equal / less or equal |
Example
c
#include <stdio.h>
int main(void) {
int a = 8, b = 3;
printf("%d\n", a > b);
printf("%d\n", a == b);
return 0;
}Output
1 0
Logical Operators
&&(and): true when both conditions are true||(or): true when at least one is true!(not): reverses the result
Example
c
int age = 22;
int hasTicket = 1;
printf("%d\n", age >= 18 && hasTicket); // prints 1
printf("%d\n", !hasTicket); // prints 0The sizeof Operator
sizeof tells you how many bytes a type or variable uses in memory:
Example
c
#include <stdio.h>
int main(void) {
printf("int: %zu bytes\n", sizeof(int));
printf("char: %zu byte\n", sizeof(char));
return 0;
}Output
int: 4 bytes char: 1 byte
The size of int can be different on some systems, but 4 bytes is the usual value on modern computers.
Exercise
Exercise
What is the value of 23 % 4 in C?
