02. Relational Operators in C

🟢 Difficulty: Beginner | Comparison Operators & Boolean Integer Logic

📖 Definition

Relational operators in C compare two operands to test relationship rules (such as equality, inequality, or magnitude ordering). In C, relational expressions evaluate strictly to an int value: 1 representing true and 0 representing false.

🎯 Why It Is Used

  • Control Flow Decision Making: Forms logical conditions in if statements, while loops, and for termination checks.
  • Boundary Validation: Ensures indices stay within array bounds (e.g. index < length).

⚙️ How It Works: Boolean Evaluation in ISO C

Prior to C99, C did not have a native boolean type. Instead, C treats zero (0) as false, and any non-zero value (such as 1, -5, or 100) as true. All relational operators evaluate to integer 1 when true and integer 0 when false.

📝 Syntax & Relational Operators Table

Operator Meaning Example (a=10, b=20) Evaluated Result
==Equal Toa == b0 (False)
!=Not Equal Toa != b1 (True)
>Greater Thana > b0 (False)
<Less Thana < b1 (True)
>=Greater Than or Equal Toa >= b0 (False)
<=Less Than or Equal Toa <= b1 (True)

🔀 The Chained Comparison Trap in C

In mathematics, 1 < x < 10 checks if x is between 1 and 10. In C, however, operators evaluate from left to right! (1 < x) < 10 first evaluates 1 < x to 0 or 1, and then compares that 0 or 1 with 10 (which is ALWAYS true!). To chain comparisons in C, you must use logical AND: (x > 1 && x < 10).

🌱 Beginner Example

#include <stdio.h>

int main(void) {
    int score = 85;
    int passing_score = 60;

    int is_passed = (score >= passing_score);
    printf("Passed Exam Test Result (1=True, 0=False): %d\n", is_passed);
    return 0;
}

🌼 Intermediate Example: Chained Comparison Bug Demonstration

#include <stdio.h>

int main(void) {
    int val = 25;

    // INCORRECT Chained Comparison in C
    if (10 < val < 20) {
        printf("Bugged check passed! (Because (10 < 25) evaluated to 1, and (1 < 20) is 1!)\n");
    }

    // CORRECT Logical Comparison in C
    if (val > 10 && val < 20) {
        printf("Value is between 10 and 20.\n");
    } else {
        printf("Correct check: Value %d is NOT between 10 and 20!\n", val);
    }
    return 0;
}

🌲 Advanced Example: Safe Float Comparison & Yoda Conditions

#include <stdio.h>
#include <math.h>

int main(void) {
    int status_code = 200;

    // "Yoda Condition": Putting constant on left prevents accidental assignment bugs (status_code = 200)
    if (200 == status_code) {
        printf("HTTP Status OK (Yoda condition check passed)\n");
    }

    double sensor_reading = 98.6;
    double calibrated_value = 98.6000001;

    // Comparing floats with epsilon
    if (fabs(sensor_reading - calibrated_value) < 1e-5) {
        printf("Sensor readings match within calibration tolerance!\n");
    }
    return 0;
}

🔍 Line-by-Line Explanation

  • int is_passed = (score >= passing_score);: Evaluates 85 >= 60, resulting in integer 1.
  • if (10 < val < 20): Demonstrates C operator left-associativity bug. 10 < 25 becomes 1, then 1 < 20 becomes 1 (true).
  • if (200 == status_code): Yoda condition pattern; if you accidentally type = instead of ==, the compiler raises a syntax error rather than making an accidental assignment.

💻 Expected Terminal Output

Passed Exam Test Result (1=True, 0=False): 1
Bugged check passed! (Because (10 < 25) evaluated to 1, and (1 < 20) is 1!)
Correct check: Value 25 is NOT between 10 and 20!
HTTP Status OK (Yoda condition check passed)
Sensor readings match within calibration tolerance!

⚠️ Common Mistakes & Pitfalls

  • Confusing Assignment = with Equality ==: Writing if (x = 5) assigns 5 to x and evaluates as true! Always use == for comparison.
  • Writing Mathematical Chained Inequalities: Writing a < b < c instead of a < b && b < c.
  • Direct Floating-Point Equality: Using == on floating point numbers due to IEEE 754 precision rounding.

📌 Important Rules & Limitations

  • Relational operators have lower precedence than arithmetic operators (e.g. a + 2 > b evaluates a + 2 first).
  • Relational expression results are guaranteed by ISO C to be integer 0 or integer 1.

🌐 Multilingual Explanation: English

Relational operators test equality and magnitude. They return 1 for true and 0 for false. Avoid writing 1 < x < 10; use (x > 1 && x < 10) instead.

🌐 Multilingual Explanation: Hindi (Roman Script)

Relational operators values ki tulna karne ke liye use hote hain aur result 1 (true) ya 0 (false) dete hain. Accidental assignment se bachne ke liye = aur == ke beech ka farak samjhein.

🌐 Multilingual Explanation: Marathi (Roman Script)

Relational operators don values tulna kartat. Tyanchi uttar hamesha 1 (barobar) kiva 0 (chuki) aste. Equality check sathi == vapartat.

❓ Practice Questions

  1. Why does the expression 5 < 2 < 1 evaluate to 1 (true) in C?
  2. What is a Yoda condition and why do developers use it?
  3. What value is assigned to int result = (10 != 10);?

🚀 Practical Coding Challenge

Write a C program named speed_checker.c that prompts for a driver's speed in km/h. Print 0 (false) if speed is within the limit (<= 80), and 1 (true) if speed exceeds 80 km/h, using a relational expression.

🧭 Navigation & Breadcrumbs

← Previous: 01. Arithmetic Operators | Module 05 Guide | Next: 03. Logical Operators →