C Relational Operators


In C language, relational operators are used to compare two values or variables. The result of a relational operation is either true (non-zero value, usually 1) or false (0). Relational operators are crucial for decision-making in programs, often used in conditional statements like if, while, etc.

List of Relational Operators

  1. Equal to (==):

    • Checks if two operands are equal.
    • Example:
      int a = 5, b = 5; if (a == b) { // This block will execute because a is equal to b }
  2. Not equal to (!=):

    • Checks if two operands are not equal.
    • Example:
      int a = 5, b = 3; if (a != b) { // This block will execute because a is not equal to b }
  3. Greater than (>):

    • Checks if the first operand is greater than the second.
    • Example:
      int a = 10, b = 5; if (a > b) { // This block will execute because a is greater than b }
  4. Less than (<):

    • Checks if the first operand is less than the second.
    • Example:
      int a = 3, b = 5; if (a < b) { // This block will execute because a is less than b }
  5. Greater than or equal to (>=):

    • Checks if the first operand is greater than or equal to the second.
    • Example:
      int a = 5, b = 5; if (a >= b) { // This block will execute because a is equal to b }
  6. Less than or equal to (<=):

    • Checks if the first operand is less than or equal to the second.
    • Example:
      int a = 4, b = 5; if (a <= b) { // This block will execute because a is less than b }

Usage in Conditions

Relational operators are most commonly used in if, while, for, and similar control structures to control the flow of the program based on comparisons:

#include <stdio.h> int main() { int x = 10, y = 20; if (x < y) { printf("x is less than y\n"); } if (x == y) { printf("x is equal to y\n"); } else { printf("x is not equal to y\n"); } return 0; }

Important Points

  1. Return Value: The result of a relational operation is either 1 (true) or 0 (false).
  2. Chaining Operators: Relational operators are generally not chained in C. Expressions like a < b < c won't behave as expected, as they are evaluated from left to right. It is better to use logical operators in such cases:
    if (a < b && b < c) { // Correct way to check if a < b and b < c }

Summary

  • ==: Checks if two values are equal.
  • !=: Checks if two values are not equal.
  • >: Checks if the left value is greater than the right value.
  • <: Checks if the left value is less than the right value.
  • >=: Checks if the left value is greater than or equal to the right value.
  • <=: Checks if the left value is less than or equal to the right value.

These relational operators are essential for controlling program logic, making decisions based on comparisons between variables and values.