Operators in C (Lesson)
Operators in C
Operators are symbols that tell the compiler to perform specific mathematical or logical manipulations.
5.1 Arithmetic Operators
Used for mathematical calculations.
| Operator | Description | Example (a=10, b=3) |
|---|---|---|
+ | Addition | a + b = 13 |
- | Subtraction | a - b = 7 |
* | Multiplication | a * b = 30 |
/ | Division | a / b = 3 (int division) |
% | Modulus (Remainder) | a % b = 1 |
5.2 Relational Operators
Used to compare two values. They return 1 (true) or 0 (false).
==(Equal to)!=(Not equal to)>(Greater than)<(Less than)>=(Greater than or equal to)<=(Less than or equal to)
5.3 Logical Operators
Used to combine multiple conditions.
&&(Logical AND): True if both are true.||(Logical OR): True if at least one is true.!(Logical NOT): Reverses the state.
5.4 Assignment Operators
Used to assign values to variables.
=: Simple assignment (a = b)+=: Add and assign (a += bisa = a + b)-=,*=,/=,%=: Similar behavior.
5.5 Increment and Decrement Operators
++(Increment): Increases value by 1.- Prefix (
++a): Increment first, then use. - Postfix (
a++): Use first, then increment.
- Prefix (
--(Decrement): Decreases value by 1.
5.6 Conditional (Ternary) Operator
The only operator in C that takes three operands.
Syntax: condition ? expression1 : expression2;
int max = (a > b) ? a : b;
5.7 Bitwise Operators
Used for manipulation of data at the bit level.
&(AND),|(OR),^(XOR),~(NOT),<<(Left shift),>>(Right shift).
5.8 Special Operators
sizeof(): Returns the size of a data type in bytes.&(Address-of): Returns the address of a variable.*(Pointer-to): Pointer to a variable.
Example: Using Various Operators
#include <stdio.h>
int main() {
int a = 10, b = 20, res;
// Arithmetic
printf("Addition: %d\n", a + b);
// Logical
if (a < b && a > 0) {
printf("Condition is true\n");
}
// Ternary
res = (a > b) ? a : b;
printf("Higher value is %d\n", res);
// Sizeof
printf("Size of int: %lu bytes\n", sizeof(int));
return 0;
}
Check the Lecture Slides for Operator Precedence and Associativity tables.