Operators: Arithmetic, Relational, Logical, Bitwise
C operators provide direct control over arithmetic calculations, boolean logic, and binary bitwise registers.
What is it?
Symbols that perform operations on variables and values. C provides high-speed operators mapping directly to assembly instructions.
Why is it used?
Powers calculations, bit manipulation, encryption algorithms, and device hardware masks.
Detailed Explanation
C Operator Categories:
• Arithmetic: `+`, `-`, `*`, `/` (integer division if both operands are ints!), `%` (modulo - integers only!).
• Relational: `==`, `!=`, `>`, `<`, `>=`, `<=`.
• Logical: `&&` (AND), `||` (OR), `!` (NOT). In C, `0` represents False, and any non-zero number represents True.
• Increment/Decrement: `++x` (pre-increment), `x++` (post-increment).
• Bitwise Operators (operating at binary bit level):
• `&` (Bitwise AND)
• `|` (Bitwise OR)
• `^` (Bitwise XOR)
• `~` (Bitwise NOT)
• `<<` (Left shift by bits: multiplies by 2)
• `>>` (Right shift by bits: divides by 2)
Syntax Structure
Syntax Blueprint
int result = (a > b) && (c != 0);
int shifted = 1 << 3; // 8
Code Example
C Code
#include <stdio.h>
int main() {
int a = 17;
int b = 5;
// Arithmetic with integer division vs float casting
printf("Integer Division: 17 / 5 = %d\n", a / b); // 3 (truncated)
printf("Modulo Remainder: 17 %% 5 = %d\n", a % b); // 2
printf("Float Division: 17 / 5 = %.2f\n", (float)a / b); // 3.40
// Bitwise Operations: Fast powers of 2
int num = 4;
int multiplied_by_2 = num << 1; // 4 * 2 = 8
int divided_by_2 = num >> 1; // 4 / 2 = 2
printf("\n--- Bitwise Shifts ---\n");
printf("4 << 1 (Left Shift): %d\n", multiplied_by_2);
printf("4 >> 1 (Right Shift): %d\n", divided_by_2);
return 0;
}
Explanation of the Code
• `17 / 5` truncates decimals because both operands are integers.
• `(float)a / b` uses explicit type casting to obtain a precise decimal quotient.
• Bitwise shift `<< 1` doubles values at machine code execution speed.
Expected Output
Integer Division: 17 / 5 = 3
Modulo Remainder: 17 % 5 = 2
Float Division: 17 / 5 = 3.40
--- Bitwise Shifts ---
4 << 1 (Left Shift): 8
4 >> 1 (Right Shift): 2
Real-World Application
Bitwise operations are used to set hardware register flags in robotics, microcontrollers, and graphics pixel shaders.
Common Mistakes to Avoid
• Confusing logical `&&` with bitwise `&` (or `||` with `|`).
• Expecting `17 / 5` to produce `3.4` without type casting one of the operands to `float`.
Quick Practice Challenge
Calculate `1 << 4` (2 to the power of 4) using bitwise left shift in C.
Key Takeaways
• Integer division in C truncates the fractional part.
• Cast at least one operand to `float` for decimal division.
• Use bitwise shifts `<<` and `>>` for ultra-fast multiplication/division by powers of 2.