Skip to main content

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.

What You'll Learn

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:

OperatorMeaningExample (a=10, b=3)Result
+Additiona + b13
-Subtractiona - b7
*Multiplicationa * b30
/Divisiona / b3 (Integer division drops remainder!)
%Modulo (Remainder)a % b1 (10 divided by 3 leaves remainder 1)
Modulo Rule

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.

OperatorMeaningExample (a=10, b=3)Result
==Equal toa == b0 (False)
!=Not equal toa != b1 (True)
>Greater thana > b1 (True)
<Less thana < b0 (False)
>=Greater than or equal toa >= 101 (True)
<=Less than or equal tob <= 20 (False)

3. Logical Operators

Used to combine relational expressions. Like relational operators, they return 1 or 0.

OperatorMeaningDescriptionExample (a=10, b=3)Result
&&Logical ANDReturns True only if both operands are True.(a > 5) && (b < 5)1
||Logical ORReturns True if at least one operand is True.(a < 5) || (b < 5)1
!Logical NOTReverses the logical state (True becomes False, and vice-versa).!(a > 5)0
Short-Circuit Evaluation

C uses short-circuit evaluation for && and ||.

  • In A && B, if A is False, C won't evaluate B because the overall result is already False.
  • In A || B, if A is True, C won't evaluate B because 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 StatementEvaluated Value of ExpressionNew Value of Variable a in memory
int x = ++a;66
int y = a++;67

5. Bitwise Operators

Bitwise operators perform logic at the individual bit (binary) level.

OperatorNameDescriptionExample (a=5 [0101], b=3 [0011])Result
&Bitwise ANDSets bit to 1 if both bits are 1.a & b1 (0001)
|Bitwise ORSets bit to 1 if either bit is 1.a | b7 (0111)
^Bitwise XORSets bit to 1 if bits are different.a ^ b6 (0110)
~Bitwise NOTFlips all bits.~a-6 (2's complement representation)
<<Left ShiftShifts bits left, filling with zeros.a << 110 (1010) (Multiplies by 2)
>>Right ShiftShifts bits right.a >> 12 (0010) (Divides by 2)

6. Assignment Operators

Used to assign values. Compound Assignment Operators combine math with assignment:

  • a = b (Assign b to a)
  • a += b (Same as a = a + b)
  • a -= b (Same as a = a - b)
  • a *= b (Same as a = a * b)
  • a /= b (Same as a = 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)

RankOperator GroupOperatorsAssociativity
1Postfix(), [], ->, ., ++ (post), -- (post)Left-to-Right
2Unary++ (pre), -- (pre), +, -, !, ~, sizeof, & (address-of), * (dereference)Right-to-Left
3Multiplicative*, /, %Left-to-Right
4Additive+, -Left-to-Right
5Shift<<, >>Left-to-Right
6Relational<, <=, >, >=Left-to-Right
7Equality==, !=Left-to-Right
8Bitwise AND&Left-to-Right
9Bitwise XOR^Left-to-Right
10Bitwise OR|Left-to-Right
11Logical AND&&Left-to-Right
12Logical OR||Left-to-Right
13Ternary?:Right-to-Left
14Assignment=, +=, -=, *=, /=, %=, etc.Right-to-Left
15Comma,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;:

StepOperators PresentPrecedence HierarchyAction TakenCurrent Expression State
1+, ** is higher rank than +Multiply 2 and 3.10 + 6
2+Only + remainingAdd 10 and 6.16
3=Assignment rankAssign 16 to mathResult.mathResult = 16

🧪 Interactive Elements

Try It Yourself

Hands-on Exercise: Complex Precedence

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

Quick Quiz: Logical Short-Circuit

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 🟢

  1. Write a C program to calculate the area and perimeter of a rectangle. Accept input lengths from the user.
  2. Fix the error in this code:
    int main() {
    float val = 7.5;
    int rem = val % 2;
    return 0;
    }

Medium Level 🟡

  1. 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 % 10 and / 10 operators.

Hard Level 🔴

  1. Predict the final output of the following variable values and check via compiling:
    int x = 10, y = 20, z;
    z = x++ + ++y - x-- + --y;
    Provide a detailed trace table showing the states after each sub-operation.

❓ 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) + z instead of x * y + z to 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: Writing if(a = 5) instead of if(a == 5). The first assigns 5 to a, evaluates to true, and creates a logical bug.
  • Modulo with float: Attempting 5.0 % 2.0 instead 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) or 0 (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:


---

📍 Visit Us

🏫 VD Computer Tuition Surat

VD Computer Tuition
📍 Address
2/66 Faram Street, Rustompura
Surat395002, Gujarat, India
📞 Phone / WhatsApp
+91 84604 41384
🌐 Website

Computer Classes & Tuition — Areas We Serve in Surat

AdajanAlthanAmroliAthwaAthwalinesBhagalBhatarBhestanCanal RoadChowkCitylightDumasGaurav PathGhod Dod RoadHaziraJahangirpuraKamrejKapodraKatargamLimbayatMagdallaMajura GateMota VarachhaNanpuraNew CitylightOlpadPalPandesaraParle PointPiplodPunaRanderRing RoadRustampuraSachinSalabatpuraSarthanaSosyo CircleUdhnaVarachhaVed RoadVesuVIP Road
📞 Call Sir💬 WhatsApp Sir