Special Operators
In C, special operators refer to operators that don't fit into the usual arithmetic, relational, logical, or bitwise categories. These operators have unique roles in programming.
Comma Operator: ,
The comma operator allows multiple expressions to be evaluated in a single statement, with the result being the value of the last expression.
#include <stdio.h>
int main() {
int a, b, c;
a = (b = 10, c = 20, b + c); // b = 10, c = 20, a = b + c
printf("a = %d, b = %d, c = %d\n", a, b, c);
return 0;
}
Output
a = 30, b = 10, c = 20
Pointer Operators * and &
These operators are used in pointer operations:
- * (dereference): Access the value at the address stored in a pointer.
- & (address-of): Get the memory address of a variable.
#include <stdio.h>
int main() {
int x = 10;
int *ptr = &x; // Pointer to x
int y = *ptr; // Dereferencing ptr
printf("x = %d, Address of x = %p, Value at ptr = %d\n", x, ptr, y);
return 0;
}
Output
x = 10, Address of x = 0x7ffdec2ad4, Value at ptr = 10
Sizeof Operator:
The sizeof operator is used to determine the size (in bytes) of a data type or variable.
#include <stdio.h>
int main() {
int a;
printf("Size of int: %zu bytesn", sizeof(a));
return 0;
}
Output
Size of int: 4 bytes
Ternary (Conditional) Operator ? :
This operator is shorthand for an if-else statement.
#include <stdio.h>
int main() {
int a = 10, b = 20;
int max = (a > b) ? a : b; // Find the larger value
printf("Max value = %d\n", max);
return 0;
}
Output
Max value = 20
Type Cast Operator :
Used to explicitly convert a value from one data type to another.
#include <stdio.h>
int main() {
int a = 5, b = 2;
float result = (float)a / b; // Casting a to float
printf("Result = %.2f\n", result);
return 0;
}
Output
Result = 2.50