0
0
CHow-ToBeginner · 3 min read

How to Use Relational Operators in C: Syntax and Examples

In C, relational operators compare two values and return either 1 (true) or 0 (false). Common operators include == (equal), != (not equal), < (less than), > (greater than), <= (less than or equal), and >= (greater than or equal). They are used in conditions to control program flow.
📐

Syntax

Relational operators compare two values and return 1 if the condition is true, or 0 if false.

Here are the operators and their meanings:

  • ==: equal to
  • !=: not equal to
  • <: less than
  • >: greater than
  • <=: less than or equal to
  • >=: greater than or equal to

They are used between two expressions, like expression1 operator expression2.

c
int result = (a == b);  // result is 1 if a equals b, else 0
int check = (x > y);     // check is 1 if x is greater than y, else 0
💻

Example

This example shows how to use relational operators to compare two numbers and print the results.

c
#include <stdio.h>

int main() {
    int a = 5, b = 10;

    printf("a == b: %d\n", a == b);
    printf("a != b: %d\n", a != b);
    printf("a < b: %d\n", a < b);
    printf("a > b: %d\n", a > b);
    printf("a <= b: %d\n", a <= b);
    printf("a >= b: %d\n", a >= b);

    return 0;
}
Output
a == b: 0 a != b: 1 a < b: 1 a > b: 0 a <= b: 1 a >= b: 0
⚠️

Common Pitfalls

One common mistake is using = (assignment) instead of == (comparison). This causes unexpected behavior because = sets a value instead of comparing.

Also, relational operators return 1 or 0, not true/false keywords.

c
/* Wrong: assigns 5 to a, then checks if a is nonzero (always true) */
if (a = 5) {
    printf("This always runs because a is assigned 5.\n");
}

/* Right: compares a to 5 */
if (a == 5) {
    printf("This runs only if a equals 5.\n");
}
📊

Quick Reference

OperatorMeaningExampleResult if a=3, b=5
==Equal toa == b0
!=Not equal toa != b1
<Less thana < b1
>Greater thana > b0
<=Less than or equal toa <= b1
>=Greater than or equal toa >= b0

Key Takeaways

Use relational operators to compare two values and get 1 (true) or 0 (false).
Remember to use == for comparison, not = which is assignment.
Relational operators work with numbers and expressions in conditions.
They help control program flow by making decisions based on comparisons.
Common operators include ==, !=, <, >, <=, and >=.