C Operators
Operators are symbols that do some operation on values (called operands). C has many types of operators.
Arithmetic operators
| Operator | Meaning | Example |
|---|---|---|
+ | Add | a + b |
- | Subtract | a - b |
* | Multiply | a * b |
/ | Divide | a / b |
% | Remainder (modulus) | a % b |
#include <stdio.h>
int main(void) {
int a = 17, b = 5;
printf("%d + %d = %d\n", a, b, a + b);
printf("%d - %d = %d\n", a, b, a - b);
printf("%d * %d = %d\n", a, b, a * b);
printf("%d / %d = %d\n", a, b, a / b);
printf("%d %% %d = %d\n", a, b, a % b);
return 0;
}
Output:
17 + 5 = 22
17 – 5 = 12
17 * 5 = 85
17 / 5 = 3
17 % 5 = 2
Relational operators
They compare two values. The result is 1 (true) or 0 (false).
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal |
<= | Less than or equal |
Logical operators
&& (AND), || (OR) and ! (NOT) join conditions.
#include <stdio.h>
int main(void) {
int age = 20, marks = 55;
printf("%d\n", age > 18 && marks >= 50); // both true
printf("%d\n", age < 18 || marks >= 50); // one true
printf("%d\n", !(age > 18)); // NOT
printf("%d\n", age == 21);
return 0;
}
Output:
1
1
0
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 |
Increment and decrement
++ adds 1 and -- subtracts 1. If it is written before the variable (prefix), the value changes first. If it is after (postfix), the old value is used first.
#include <stdio.h>
int main(void) {
int x = 5;
printf("%d\n", x++); // prints 5, then x becomes 6
printf("%d\n", x); // 6
printf("%d\n", ++x); // x becomes 7, then prints 7
return 0;
}
Output:
5
6
7
Ternary operator
It is a short form of if else: condition ? value_if_true : value_if_false.
#include <stdio.h>
int main(void) {
int marks = 42;
printf("%s\n", marks >= 40 ? "Pass" : "Fail");
return 0;
}
Output:
Pass
Bitwise operators
They work on the bits of integers: & AND, | OR, ^ XOR, ~ NOT, << left shift and >> right shift.
#include <stdio.h>
int main(void) {
int a = 12, b = 10; // 1100 and 1010
printf("%d\n", a & b); // 1000
printf("%d\n", a | b); // 1110
printf("%d\n", a ^ b); // 0110
printf("%d\n", a << 1); // 11000
printf("%d\n", a >> 2); // 11
return 0;
}
Output:
8
14
6
24
3
Operator precedence
When many operators are in one expression, C follows an order. Multiplication, division and remainder come before addition and subtraction. Use brackets when you are not sure.
#include <stdio.h>
int main(void) {
printf("%d\n", 10 + 5 * 2); // 20
printf("%d\n", (10 + 5) * 2); // 30
return 0;
}
Output:
20
30
Next: C If Else Statement.