Ad Space
Operators are symbols that perform operations on variables and values. C supports different types of operators, grouped as follows:
Used for mathematical operations.
| Operator | Meaning |
|---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus |
#include <stdio.h>
int main() {
int a = 10, b = 3;
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
printf("a %% b = %d\n", a % b);
return 0;
}
Output:
a + b = 13 a - b = 7 a * b = 30 a / b = 3 a % b = 1
Used to compare values. They return 1 (true) or 0 (false).
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
int x = 5, y = 10;
printf("%d\n", x > y); // 0 (false)
printf("%d\n", x < y); // 1 (true)
Used for logical conditions.
| Operator | Meaning |
|---|---|
&& | Logical AND |
|| | Logical OR |
! | Logical NOT |
int a = 5, b = 10;
printf("%d\n", (a > 0 && b > 0)); // 1 (true)
printf("%d\n", (a > 0 || b < 0)); // 1 (true)
printf("%d\n", !(a > 0)); // 0 (false)
Used to assign values.
| Operator | Example | Equivalent |
|---|---|---|
= | a = 10 | a = 10 |
+= | a += 5 | a = a + 5 |
-= | a -= 5 | a = a - 5 |
*= | a *= 5 | a = a * 5 |
/= | a /= 5 | a = a / 5 |
%= | a %= 5 | a = a % 5 |
Used to increment or decrement a value by 1.
| Operator | Meaning |
|---|---|
++ | Increments by 1 |
-- | Decrements by 1 |
int a = 5;
printf("%d\n", a++); // 5 (post-increment, a becomes 6)
printf("%d\n", ++a); // 7 (pre-increment, a becomes 7)
Used as a shorthand for if-else.
Syntax:condition ? expr1 : expr2;
Example:
int a = 10, b = 20;
int largest = (a > b) ? a : b;
printf("Largest = %d", largest);
Output:
Largest = 20
Work at the bit level.
| Operator | Meaning |
|---|---|
& | Bitwise AND |
| | Bitwise OR |
^ | Bitwise XOR |
~ | Bitwise NOT (Complement) |
<< | Left shift |
>> | Right shift |
#include <stdio.h>
int main() {
int a = 10, b = 20;
// Arithmetic
printf("a + b = %d\n", a + b);
// Relational
printf("a > b = %d\n", a > b); // 0 (false)
// Logical
printf("(a > 0 && b > 0) = %d\n", (a > 0 && b > 0)); // 1 (true)
// Assignment
a += 5; // a is now 15
printf("a after += 5: %d\n", a);
// Conditional
int max = (a > b) ? a : b; // a is 15, b is 20
printf("Largest = %d\n", max); // max will be 20
return 0;
}
Ad Space