Operators in C ⚙️
Operators in C: Arithmetic, Logical, Bitwise & Precedence is a core C concept covering a complete guide to C operators. Master arithmetic, relational, logical, bitwise, assignment, ternary, and increment/decrement operators, plus operator precedence. This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.
Mentor's Note: Operators are the verbs of the programming language. Variables are the nouns, and operators are the actions we perform on them. To write complex formulas, you must know how they work and which runs first! 💡
📚 Educational Content: This tutorial is designed to align with GSEB Std 10/12, CBSE Computer Science, and BCA Sem 1 syllabus standards.
By the end of this tutorial, you'll know:
- How to use arithmetic, relational, logical, and assignment operators.
- The precise difference between pre-increment (
++x) and post-increment (x++). - How bitwise operators manipulate data at the raw binary level.
- How to write short conditional code using the Ternary (Conditional) operator.
- The operator precedence and associativity rules to solve complex equations (highly tested in exams).
🌟 The Scenario: The Calculator Machine
Imagine a factory processing assembly line. Raw materials (variables and values) enter, and various machines (operators) modify them:
- The Adder/Multiplier: Performs calculations on raw materials.
- The Inspector: Compares two parts (relational) and routes them based on size (logical rules).
- The Priority Controller: Decides which machine goes first. If a multiplication machine and addition machine are waiting, the priority controller always feeds raw materials to the multiplication machine first (Precedence).
Without operators, your variables are static boxes sitting on shelves. Operators are the machinery that performs actual work.
📖 Concept Explanation
C provides a rich set of operators to manipulate data. They can be classified based on the number of operands they take:
- Unary Operators: Work on a single operand (e.g.
++x,-x). - Binary Operators: Work on two operands (e.g.
x + y,x > y). - Ternary Operators: Work on three operands (e.g.
condition ? x : y).
Let's examine each group.
1. Arithmetic Operators
Used to perform mathematical operations:
| Operator | Meaning | Example (a=10, b=3) | Result |
|---|---|---|---|
+ | Addition | a + b | 13 |
- | Subtraction | a - b | 7 |
* | Multiplication | a * b | 30 |
/ | Division | a / b | 3 (Integer division drops remainder!) |
% | Modulo (Remainder) | a % b | 1 (10 divided by 3 leaves remainder 1) |
The modulo operator % can only be used with integer types. Using % with a float or double (like 5.5 % 2) will cause a compile-time error.
2. Relational Operators
Used to compare two values. In C, relational operations return an integer value: 1 for True and 0 for False.
| Operator | Meaning | Example (a=10, b=3) | Result |
|---|---|---|---|
== | Equal to | a == b | 0 (False) |
!= | Not equal to | a != b | 1 (True) |
> | Greater than | a > b | 1 (True) |
< | Less than | a < b | 0 (False) |
>= | Greater than or equal to | a >= 10 | 1 (True) |
<= | Less than or equal to | b <= 2 | 0 (False) |
3. Logical Operators
Used to combine relational expressions. Like relational operators, they return 1 or 0.
| Operator | Meaning | Description | Example (a=10, b=3) | Result |
|---|---|---|---|---|
&& | Logical AND | Returns True only if both operands are True. | (a > 5) && (b < 5) | 1 |
|| | Logical OR | Returns True if at least one operand is True. | (a < 5) || (b < 5) | 1 |
! | Logical NOT | Reverses the logical state (True becomes False, and vice-versa). | !(a > 5) | 0 |
C uses short-circuit evaluation for && and ||.
- In
A && B, ifAis False, C won't evaluateBbecause the overall result is already False. - In
A || B, ifAis True, C won't evaluateBbecause the overall result is already True.
4. Increment and Decrement Operators
These unary operators add or subtract 1 from a variable.
- Pre-increment/decrement (
++a,--a): Change the variable's value first, then evaluate it in the expression. - Post-increment/decrement (
a++,a--): Evaluate the expression with the current value first, then change the variable's value.
Pre- vs Post-Increment Trace Table (int a = 5;)
| Code Statement | Evaluated Value of Expression | New Value of Variable a in memory |
|---|---|---|
int x = ++a; | 6 | 6 |
int y = a++; | 6 | 7 |
5. Bitwise Operators
Bitwise operators perform logic at the individual bit (binary) level.
| Operator | Name | Description | Example (a=5 [0101], b=3 [0011]) | Result |
|---|---|---|---|---|
& | Bitwise AND | Sets bit to 1 if both bits are 1. | a & b | 1 (0001) |
| | Bitwise OR | Sets bit to 1 if either bit is 1. | a | b | 7 (0111) |
^ | Bitwise XOR | Sets bit to 1 if bits are different. | a ^ b | 6 (0110) |
~ | Bitwise NOT | Flips all bits. | ~a | -6 (2's complement representation) |
<< | Left Shift | Shifts bits left, filling with zeros. | a << 1 | 10 (1010) (Multiplies by 2) |
>> | Right Shift | Shifts bits right. | a >> 1 | 2 (0010) (Divides by 2) |
6. Assignment Operators
Used to assign values. Compound Assignment Operators combine math with assignment:
a = b(Assignbtoa)a += b(Same asa = a + b)a -= b(Same asa = a - b)a *= b(Same asa = a * b)a /= b(Same asa = a / b)
7. Ternary (Conditional) Operator
The only operator in C that takes three arguments. It is a shorthand for an if-else statement:
condition ? expression_if_true : expression_if_false;
Example:
int max = (a > b) ? a : b;
If a > b is true, max becomes a. Otherwise, max becomes b.
📊 Operator Precedence and Associativity
When an expression contains multiple operators (like x = 5 + 3 * 2), C uses rules to determine which operator evaluates first.
- Precedence: Order of priority (like BODMAS).
- Associativity: Order of evaluation (Left-to-Right or Right-to-Left) when operators have the same precedence level.
Operator Priority Table (Highest to Lowest)
| Rank | Operator Group | Operators | Associativity |
|---|---|---|---|
| 1 | Postfix | (), [], ->, ., ++ (post), -- (post) | Left-to-Right |
| 2 | Unary | ++ (pre), -- (pre), +, -, !, ~, sizeof, & (address-of), * (dereference) | Right-to-Left |
| 3 | Multiplicative | *, /, % | Left-to-Right |
| 4 | Additive | +, - | Left-to-Right |
| 5 | Shift | <<, >> | Left-to-Right |
| 6 | Relational | <, <=, >, >= | Left-to-Right |
| 7 | Equality | ==, != | Left-to-Right |
| 8 | Bitwise AND | & | Left-to-Right |
| 9 | Bitwise XOR | ^ | Left-to-Right |
| 10 | Bitwise OR | | | Left-to-Right |
| 11 | Logical AND | && | Left-to-Right |
| 12 | Logical OR | || | Left-to-Right |
| 13 | Ternary | ?: | Right-to-Left |
| 14 | Assignment | =, +=, -=, *=, /=, %=, etc. | Right-to-Left |
| 15 | Comma | , | Left-to-Right |
💻 Working Example: Precedence & Increment Differences
Here is a complete C program demonstrating increment operators, precedence, and short-circuit logic:
#include <stdio.h>
// 🛒 Scenario: Priority Evaluation Lab
// 🚀 Action: Tests operators precedence and pre/post-increment behaviors
int main() {
int a = 5;
int b = 10;
// Test 1: Pre vs Post Increment
int preResult = ++a; // 'a' incremented to 6 first; preResult gets 6
int postResult = b++; // postResult gets current b (10); b incremented to 11 next
printf("Pre-increment (a): %d, preResult: %d\n", a, preResult);
printf("Post-increment (b): %d, postResult: %d\n", b, postResult);
// Test 2: Precedence evaluation
// Multiplicative '*' has higher precedence than additive '+'
int mathResult = 10 + 2 * 3; // 10 + (2 * 3) = 16
printf("10 + 2 * 3 = %d\n", mathResult);
// Test 3: Short-circuiting evaluation
int x = 0;
int y = 5;
// Since x is 0 (False), the condition 'y++ > 5' is NOT evaluated
int check = (x != 0) && (y++ > 5);
printf("Check result: %d, y value: %d (should remain 5)\n", check, y);
return 0;
}
// Output:
// Pre-increment (a): 6, preResult: 6
// Post-increment (b): 11, postResult: 10
// 10 + 2 * 3 = 16
// Check result: 0, y value: 5 (should remain 5)
📊 Sample Dry Run
Let's trace how the computer resolves int mathResult = 10 + 2 * 3;:
| Step | Operators Present | Precedence Hierarchy | Action Taken | Current Expression State |
|---|---|---|---|---|
| 1 | +, * | * is higher rank than + | Multiply 2 and 3. | 10 + 6 |
| 2 | + | Only + remaining | Add 10 and 6. | 16 |
| 3 | = | Assignment rank | Assign 16 to mathResult. | mathResult = 16 |
🧪 Interactive Elements
Try It Yourself
Task: What will be the output of the following C expression? Write a short C program to check your answer.
int result = 5 + 3 * 4 / 2 - 1;
Hint: * and / have the same precedence and associate Left-to-Right. Thus, first evaluate 3 * 4 (12), then divide by 2 (6), then evaluate 5 + 6 - 1 (10).
Quick Quiz
Given int a = 1, b = 2;, what is the value of b after executing: (a == 1) || (b++ > 2)?
- A) 2
- B) 3
- C) 1
- D) Compiler Error
Explanation: Because (a == 1) is True, the logical OR || operator short-circuits. It does not evaluate the second expression (b++ > 2). Therefore, b remains unchanged with a value of 2.
📉 Complexity Analysis
- Time Complexity:
- Operator execution: $O(1)$ constant time. All fundamental operations map directly to native assembly and CPU instructions.
- Space Complexity:
- Memory consumption: $O(1)$ auxiliary space.
🎯 Practice Problems
Easy Level 🟢
- Write a C program to calculate the area and perimeter of a rectangle. Accept input lengths from the user.
- Fix the error in this code:
int main() {float val = 7.5;int rem = val % 2;return 0;}
Medium Level 🟡
- Write a C program that accepts a 3-digit integer from the user and calculates the sum of its digits (e.g.
123->6). Hint: Use% 10and/ 10operators.
Hard Level 🔴
- Predict the final output of the following variable values and check via compiling:
Provide a detailed trace table showing the states after each sub-operation.int x = 10, y = 20, z;z = x++ + ++y - x-- + --y;
❓ Frequently Asked Questions
Q: What is the difference between = and ==?
= is the assignment operator used to store a value inside a variable (like x = 5;). == is the relational equality operator used to compare two values to check if they are equal (like x == 5, which returns True or False). Mixing them up is one of the most common C bugs!
Q: Why does 5 / 2 print 2 instead of 2.5?
Because both 5 and 2 are integers, C performs integer division. In integer division, the decimal part is discarded (truncated). To get a decimal output, at least one of the numbers must be written as a float (e.g. 5.0 / 2 or 5 / 2.0), which results in 2.5.
Q: What does a bitwise shift left << do?
Bitwise shifting a number left by n positions (x << n) shifts all the bits in the binary representation of x to the left by n places. This is equivalent to multiplying the integer x by $2^n$.
📚 Best Practices & Common Mistakes
✅ Best Practices
- Use parentheses for clarity: Even if you know the exact precedence, write
(x * y) + zinstead ofx * y + zto make your code easier for others to read. - Avoid complex increment combinations: Writing code like
x = x++ + ++x;is undefined behavior in the C standard. Keep increment operations on separate lines. - Beware of integer division in formulas: In equations like
fahrenheit = (celsius * 9 / 5) + 32, make sure division happens correctly without truncation by using float values.
❌ Common Mistakes ⚠️
- Using single
=inside conditionals: Writingif(a = 5)instead ofif(a == 5). The first assigns 5 toa, evaluates to true, and creates a logical bug. - Modulo with float: Attempting
5.0 % 2.0instead of integer parameters. - Short-circuit side effects: Putting critical code that must run inside the second operand of
&&or||, which might not execute.
✅ Summary
In this tutorial, you've learned:
- ✅ Arithmetic operators handle math, and modulo
%yields the remainder. - ✅ Relational and logical operators evaluate to
1(True) or0(False). - ✅ Pre-increment modifies then evaluates; post-increment evaluates then modifies.
- ✅ Bitwise operators operate on binary structures at the bit level.
- ✅ Operators Precedence and Associativity rule the evaluation order of expressions.
💡 Pro Tip: Use compound assignment operators like
+=and*=to write cleaner, more optimized code that can be compiled directly into faster CPU instructions!
📚 Further Reading
Continue your learning path:
Go deeper:
---