C - Operators
Operators in C
Operators are special symbols that perform operations on variables and values. C provides a rich set of operators for arithmetic, comparison, logic, bitwise, assignment, and more.
Learning Objectives
- Use arithmetic, relational, logical, bitwise, and assignment operators correctly.
- Explain truthiness in C (0 is false; nonzero is true).
- Understand operator precedence at a practical level.
Prerequisites
Types of Operators
- Arithmetic (
+ - * / %) - Relational (
< > <= >= == !=) - Logical (
&& || !) - Bitwise (
& | ^ ~ << >>) - Assignment (
= += -= *= /=) - Increment/Decrement (
++ --) - Conditional (
?:)
Examples
#include <stdio.h>
int main(void) {
int a = 5, b = 2;
printf("a + b = %d\n", a + b); // 7
printf("a == b = %d\n", a == b); // 0 (false)
printf("a > b = %d\n", a > b); // 1 (true)
printf("a && b = %d\n", a && b); // 1 (true)
printf("a | b (bitwise) = %d\n", a | b); // 7
a += 3; // a = 8
printf("a after += 3: %d\n", a);
int max = (a > b) ? a : b;
printf("max = %d\n", max);
return 0;
}
Common Pitfalls
- Confusing assignment (
=) with equality (==). - Assuming
trueis 1 specifically; any nonzero is true. - Forgetting that
&&and||short-circuit.
Checks for Understanding
- What is the result of
5 / 2in C? Why? - When does
a && bevaluateb?
Show answers
- It’s 2 (integer division truncates).
- Only if
ais nonzero (true); otherwise it short-circuits.
Practice
- Write an expression using the conditional operator that returns the absolute value of
x. - Use bitwise operators to test whether an integer is odd or even.
Summary
Operators are fundamental to writing expressions and logic in C programs. Keep a mental model of precedence and use parentheses to make intent clear.