Start learning free

LESSON 69 OF 409 · CONDITIONAL STATEMENTS

Comparison Operators in C++ in C++

Lesson Read the full explanation

When writing if statements, we usually compare two values using one or more comparison operators:

Operator Name Examples
== Equal  x == 5,  x == y
!= Not equal  x != 3,  x != y
> Greater than  x > 5,  x > y
< Less than  x < 8,  x < y
>= Greater than or equal to  x >= 4,  x >= y
<= Less than or equal to  x <= 3,   x <= y

For example:

10 == 10 // Evaluates to true
3 < 2 // Evaluates to false
15 >= 15 // Evaluates to true
17 != 12 // Evaluates to true

We usually use these operators with variables:

int a = 10;
int b = 15;

if (a == b) {
    cout << "a is equal to b";
}
if (a < b) {
    cout << "a is less than b";
}

The first condition is not satisfied since 10 == 15 evaluates to false.

The second condition is satisfied since 10 < 15 evaluates to true.

The code above prints "a is less than b".


Assignment
Follow the Coding Tutorial and let's play with comparison operators.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    C++ · CONDITIONAL STATEMENTS

    Comparison Operators in C++, explained

    Introduction

    In this lesson, we will explore comparison operators in C++. Comparison operators are fundamental in programming as they allow us to compare two values and make decisions based on the result of the comparison. These operators are essential in control flow statements like if and while loops, enabling us to execute code conditionally.

    Understanding comparison operators is crucial for tasks such as sorting, searching, and validating input. They are widely used in various applications, from simple scripts to complex algorithms.

    Understanding the Basics

    Comparison operators in C++ are used to compare two values. The result of a comparison is a boolean value: true or false. Here are the basic comparison operators:

    • ==: Equal to
    • !=: Not equal to
    • >: Greater than
    • <: Less than
    • >=: Greater than or equal to
    • <=: Less than or equal to

    Before diving into more complex scenarios, it's important to understand these basic operators and how they work with different data types.

    Main Concepts

    Let's define and explain the key concepts and techniques involved in using comparison operators:

    • Equality Comparison: Checks if two values are equal using ==.
    • Inequality Comparison: Checks if two values are not equal using !=.
    • Relational Comparison: Compares the relative size of two values using >, <, >=, and <=.

    These operators can be applied to various data types, including integers, floating-point numbers, and characters. The logical flow involves evaluating the expression and returning a boolean result.

    Examples and Use Cases

    Here are some examples demonstrating the use of comparison operators in different contexts:

    #include <iostream>
    using namespace std;
    
    int main() {
        int x = 10;
        int y = 20;
    
        // Equality comparison
        if (x == y) {
            cout << "x is equal to y" << endl;
        } else {
            cout << "x is not equal to y" << endl;
        }
    
        // Greater than comparison
        if (x > y) {
            cout << "x is greater than y" << endl;
        } else {
            cout << "x is not greater than y" << endl;
        }
    
        // Less than or equal to comparison
        if (x <= y) {
            cout << "x is less than or equal to y" << endl;
        } else {
            cout << "x is greater than y" << endl;
        }
    
        return 0;
    }
    

    In this example, we compare two integer variables, x and y, using different comparison operators. The output will be:

    x is not equal to y
    x is not greater than y
    x is less than or equal to y
    

    Common Pitfalls and Best Practices

    When using comparison operators, it's important to avoid common mistakes such as:

    • Using = instead of == for equality comparison.
    • Comparing floating-point numbers directly due to precision issues.
    • Not considering the data type of the variables being compared.

    Best practices include:

    • Always use == for equality comparison.
    • Use a tolerance value when comparing floating-point numbers.
    • Ensure variables are of compatible data types before comparing.

    Advanced Techniques

    Advanced techniques involve combining comparison operators with logical operators to create complex conditions. For example:

    #include <iostream>
    using namespace std;
    
    int main() {
        int a = 5;
        int b = 10;
        int c = 15;
    
        if (a < b && b < c) {
            cout << "a is less than b and b is less than c" << endl;
        }
    
        if (a == 5 || b == 5) {
            cout << "Either a or b is equal to 5" << endl;
        }
    
        return 0;
    }
    

    In this example, we use logical operators && (AND) and || (OR) to combine multiple comparison conditions.

    Code Implementation

    Here is a well-commented code snippet demonstrating the correct use of comparison operators:

    #include <iostream>
    using namespace std;
    
    int main() {
        int num1 = 25;
        int num2 = 30;
    
        // Check if num1 is equal to num2
        if (num1 == num2) {
            cout << "num1 is equal to num2" << endl;
        } else {
            cout << "num1 is not equal to num2" << endl;
        }
    
        // Check if num1 is less than num2
        if (num1 < num2) {
            cout << "num1 is less than num2" << endl;
        }
    
        // Check if num1 is greater than or equal to num2
        if (num1 >= num2) {
            cout << "num1 is greater than or equal to num2" << endl;
        } else {
            cout << "num1 is less than num2" << endl;
        }
    
        return 0;
    }
    

    This code snippet compares two integers and prints the result of each comparison.

    Debugging and Testing

    When debugging code involving comparison operators, consider the following tips:

    • Print variable values before the comparison to ensure they hold the expected values.
    • Use a debugger to step through the code and observe the evaluation of comparison expressions.

    To test functions using comparison operators, write test cases that cover different scenarios, including edge cases. For example:

    #include <iostream>
    #include <cassert>
    using namespace std;
    
    bool isEqual(int a, int b) {
        return a == b;
    }
    
    int main() {
        assert(isEqual(10, 10) == true);
        assert(isEqual(10, 20) == false);
        cout << "All test cases passed!" << endl;
        return 0;
    }
    

    This example uses assert to test the isEqual function.

    Thinking and Problem-Solving Tips

    When approaching problems involving comparison operators, consider the following strategies:

    • Break down the problem into smaller parts and solve each part individually.
    • Use flowcharts or pseudocode to plan the logic before writing actual code.
    • Practice with coding exercises and projects to reinforce your understanding.

    Conclusion

    In this lesson, we covered the basics of comparison operators in C++, including their significance, common use cases, and best practices. Mastering these operators is essential for writing efficient and effective code. Keep practicing and exploring further applications to enhance your programming skills.

    Additional Resources

    For further reading and practice problems, consider the following resources:

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free