What are the comparison operators that create boolean results in C++?

0158

In C++, comparison operators are used to compare two values and produce a boolean result (true or false). Here are the primary comparison operators:

  1. Equal to (==): Checks if two values are equal.

    if (a == b) { /* true if a is equal to b */ }
  2. Not equal to (!=): Checks if two values are not equal.

    if (a != b) { /* true if a is not equal to b */ }
  3. Less than (<): Checks if the left value is less than the right value.

    if (a < b) { /* true if a is less than b */ }
  4. Less than or equal to (<=): Checks if the left value is less than or equal to the right value.

    if (a <= b) { /* true if a is less than or equal to b */ }
  5. Greater than (>): Checks if the left value is greater than the right value.

    if (a > b) { /* true if a is greater than b */ }
  6. Greater than or equal to (>=): Checks if the left value is greater than or equal to the right value.

    if (a >= b) { /* true if a is greater than or equal to b */ }

Example Code:

#include <iostream>

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

    std::cout << "a == b: " << (a == b) << std::endl; // false
    std::cout << "a != b: " << (a != b) << std::endl; // true
    std::cout << "a < b: " << (a < b) << std::endl;   // true
    std::cout << "a <= b: " << (a <= b) << std::endl; // true
    std::cout << "a > b: " << (a > b) << std::endl;   // false
    std::cout << "a >= b: " << (a >= b) << std::endl; // false

    return 0;
}

Output:

a == b: 0
a != b: 1
a < b: 1
a <= b: 1
a > b: 0
a >= b: 0

Summary:

Comparison operators in C++ allow you to compare values and produce boolean results, which are essential for making decisions in your code. If you have further questions or need clarification, feel free to ask!

0 Comments

no data
Be the first to share your comment!