Operators and expressions
Operators and Expressions in C
In C language, operators are special symbols used to perform operations on data and variables.
An expression is a combination of operators and operands (variables/constants) that produces a result.
Example: a + b is an expression where + is an operator and a, b are operands.
1. Arithmetic Operators
These operators are used for mathematical calculations like addition, subtraction, multiplication, etc.
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;
}
a+b = 13
a-b = 7
a*b = 30
a/b = 3
a%b = 1
2. Relational Operators
These operators are used to compare two values. The result is either true (1) or false (0).
int main() {
int x = 5, y = 10;
printf("x == y : %d\\n", x == y);
printf("x != y : %d\\n", x != y);
printf("x > y : %d\\n", x > y);
printf("x < y : %d\\n", x < y);
return 0;
}
x == y : 0
x != y : 1
x > y : 0
x < y : 1
3. Logical Operators
Used to combine multiple conditions.
int main() {
int a = 1, b = 0;
printf("a && b = %d\\n", a && b);
printf("a || b = %d\\n", a || b);
printf("!a = %d\\n", !a);
return 0;
}
a && b = 0
a || b = 1
!a = 0
4. Bitwise Operators
Work on bits (0s and 1s) directly.
int main() {
int a = 5, 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 = %d\\n", ~a);
printf("a<<1 = %d\\n", a<<1);
printf("a>>1 = %d\\n", a>>1);
return 0;
}
a & b = 1
a | b = 7
a ^ b = 6
~a = -6
a<<1 = 10
a>>1 = 2
5. Assignment Operators
Used to assign values to variables.
6. Increment / Decrement Operators
Increase or decrease a variable by 1.
Prefix: ++a → increment before use, Postfix: a++ → increment after use.
7. Conditional (Ternary) Operator
Shortcut for if-else.
int main() {
int x = 10, y = 20;
int max = (x > y) ? x : y;
printf("Max = %d", max);
return 0;
}
Max = 20
8. Operator Precedence and Associativity
When multiple operators appear in one expression, precedence decides which operator executes first, and associativity decides the order when operators have the same precedence.
| Operators | Precedence | Associativity |
|---|---|---|
| () , [] , -> , . | Highest | Left to Right |
| ++ , -- , ! , ~ , sizeof | High | Right to Left |
| * , / , % | Medium | Left to Right |
| + , - | Medium | Left to Right |
| << , >> | Low | Left to Right |
| < , > , <= , >= | Lower | Left to Right |
| == , != | Lower | Left to Right |
| & | Very Low | Left to Right |
| ^ , | | Very Low | Left to Right |
| && , || | Low | Left to Right |
| ? : | Low | Right to Left |
| = , += , -= | Very Low | Right to Left |
| , (comma) | Lowest | Left to Right |
Comments
Post a Comment