Comparison Operators in C++

Comparison operators are used to compare two values. They return a Boolean value (true or false) based on the comparison result.

Key Topics

List of Comparison Operators

Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b

Examples

Example: Using Comparison Operators

#include <iostream>

int main() {
    int a = 10;
    int b = 20;
    
    std::cout << "a == b: " << (a == b) << std::endl;
    std::cout << "a != b: " << (a != b) << std::endl;
    std::cout << "a > b: " << (a > b) << std::endl;
    std::cout << "a < b: " << (a < b) << std::endl;
    std::cout << "a >= b: " << (a >= b) << std::endl;
    std::cout << "a <= b: " << (a <= b) << std::endl;
    
    return 0;
}

Output (1 for true, 0 for false):

a == b: 0

a != b: 1

a > b: 0

a < b: 1

a >= b: 0

a <= b: 1

Explanation: The program compares variables a and b using different comparison operators and outputs the results.

Key Takeaways

  • Comparison operators are essential for decision-making in code.
  • They return Boolean values (true or false).
  • Useful in conditional statements like if and loops.