Operators play a crucial role in C programming, enabling efficient computations and manipulations. Here are some key points to remember about C operators:
1. Cast Operator Precedence
The cast operator () has the same high precedence as other unary operators like sizeof, !, &, *, +, and -. This means that type conversions occur before most binary operations.
Example:
#include <stdio.h>
int main() {
int x = 10;
int y = 3;
double result = (double)x / y; // Casts x to double before division
printf("%f\n", result); // Output: 3.333333
return 0;
}
2. Increment and Decrement Operators
The increment (++) and decrement (--) operators can only be applied to variables, not to expressions or constants.
Invalid Example:
(int)10++; // Error: Cannot apply increment to a constant expression
Valid Example:
int a = 5;
a++; // Valid, modifies the variable
3. Bitwise Shift Operators
Bitwise shift operators (<<, >>) allow shifting bits left or right, typically used for performance optimizations or low-level programming.
Right Shift (>>)
The right shift operator moves bits to the right and discards excess bits. The behavior for signed integers is implementation-defined (logical or arithmetic shift).
Example:
#include <stdio.h>
int main() {
int var = 32; // Binary: 00100000
int shifted = var >> 2; // Binary: 00001000 (8 in decimal)
printf("%d\n", shifted); // Output: 8
return 0;
}
Here, var is shifted 2 positions to the right. The empty bit positions are filled with zeroes for unsigned integers.
Left Shift (<<)
The left shift operator moves bits to the left, filling the empty positions with zeros.
Example:
int b = 5; // Binary: 00000101
int c = b << 3; // Binary: 00101000 (40 in decimal)
printf("%d\n", c); // Output: 40
4. Bitwise Operators and Integral Types
Bitwise operators (&, |, ^, ~, <<, >>) can only be used with integral types (such as int, char, long). They do not work with floating-point numbers (float, double).
Invalid Example:
float f = 5.5;
int result = f >> 1; // Error: Bitwise shift not allowed on floating-point numbers
Summary
- The cast operator has the same precedence as other unary operators.
- Increment (
++) and decrement (--) apply only to variables, not expressions or constants. - Bitwise shift operators (
>>,<<) operate only on integral types and cannot be used with floating-point numbers. - The behavior of right shift on negative numbers is implementation-dependent.
By keeping these rules in mind, you can avoid common pitfalls when working with operators in C.