Computer scienceProgramming languagesC++Operators and expressions

Comparison operators

6 minutes read

Comparison operators are fundamental components of any programming language, deriving their logical foundation from mathematical principles. These operators enable developers to make logical decisions and control the flow of their code. In the context of C++, comparison operators play a pivotal role in evaluating the relationships between values and variables. This topic explores the various comparison operators in C++, and their usage, and provides code examples to illustrate their functionality.

Comparison operators

Comparison operators are symbols used in programming languages to compare two values or expressions. They help determine the relationship between these values and return a boolean result (either true or false) based on the comparison's outcome. These operators are commonly used in conditional statements, loops, and other situations where logical decisions must be made.

In C++, the primary comparison operators are: ==, !=, >, <, >=, <=. These operators are used extensively to make decisions in programming, such as checking conditions and controlling the code flow. They are not limited to just numeric values; they can also be used with strings, characters, and other data types as long as they support the comparison operation.

Now, let's discuss these operators in detail with examples.

Operators

1. Equal to (==) Operator: The equal-to operator checks if two values are equal and returns true if they are. Otherwise, it returns false. It is important to note that the equality operator checks for value equality, not necessarily for object identity.

int a = 5;
int b = 5;
bool result = (a == b); // result is true

Value equality means that the actual data contained within the variables are compared, and if they are the same, the equality comparison returns true. On the other hand, object identity refers to whether two variables or expressions refer to the same memory location. This concept is more relevant when dealing with objects and pointers.

2. Not Equal to (!=) Operator: The not equal to operator evaluates whether two values are not equal. It returns true if the values are different, and false if they are the same.

int x = 10;
int y = 20;
bool result = (x != y); // result is true

3. Greater than (>) and Less than (<) Operators: The greater than operator checks if the left-hand operand is greater than the right-hand operand. The less than operator, on the other hand, evaluates if the left-hand operand is less than the right-hand operand.

int p = 15;
int q = 8;
bool result_gt = (p > q); // result_gt is true
bool result_lt = (p < q); // result_lt is false

4. Greater than or Equal to (>=) and Less than or Equal to (<=) Operators: These operators evaluate whether the left-hand operand is greater than or equal to, or less than or equal to, the right-hand operand.

int m = 25;
int n = 25;
bool result_ge = (m >= n); // result_ge is true
bool result_le = (m <= n); // result_le is true

Behavior with different data types

You can use comparison operators in C++ with various data types, including numeric types, characters, and strings. When comparing numeric types such as integers, the behavior is straightforward – the operators evaluate the relationship between the values. For example, the greater than (>) operator checks if the left-hand operand is numerically greater than the right-hand operand.

When comparing characters, C++ compares their ASCII values. For instance, if you compare two characters using the equal to (==) operator, you are checking whether their ASCII values are the same.

In the ASCII code, the characters are typically arranged sequentially, aligning with their numerical representations. This arrangement allows for straightforward logical comparisons among characters. This enables operations such as assessing whether one character is greater than another, as in cases like a > c, b < a, and beyond.

char char1 = 'A';
char char2 = 'B';
bool result = (char1 == char2); // result is false

For strings, the comparison operators work based on lexicographic (dictionary) order. This means that strings are compared character by character until a difference is found.

string str1 = "apple";
string str2 = "banana";
bool result = (str1 < str2); // result is true

Compare with epsilon value

Comparing floating-point numbers using exact equality (==) can be problematic due to how these numbers are stored in memory and the potential for rounding errors. Floating-point arithmetic is not always exact, which can lead to unexpected results when comparing values. For example:

double num1 = 0.1 + 0.1 + 0.1;
double num2 = 0.3;
bool result = (num1 == num2); // result might be false due to precision issues

To address this issue, programmers often use an approach called "epsilon comparison." Epsilon is a small value that represents an acceptable tolerance for equality. Instead of directly comparing two floating-point numbers, you compare the absolute difference between them to a small epsilon value.

#include <iostream>

int main() {
    double num1 = 0.1 + 0.1 + 0.1;
    double num2 = 0.3;

    double epsilon = 1e-9; 
    bool result = std::abs(num1 - num2) < epsilon; // Comparing with epsilon

    if (result) {
        std::cout << "num1 and num2 are approximately equal." << std::endl;
    } else {
        std::cout << "num1 and num2 are not equal." << std::endl;
    }

    return 0;
}

Here, double epsilon = 1e-9; declares a variable named epsilon of type double and assigns it a value of 1e-9. The value 1e-9 is a scientific notation representing 1 multiplied by 10 raised to the power of -9, which is a very small number: 0.000000001.

In the above code, the absolute difference between num1 and num2 is calculated using abs(). If this absolute difference is less than the specified epsilon value (1e-9), then result will be true, indicating that the numbers are approximately equal within the defined tolerance. Otherwise, result will be false, indicating that the numbers are not equal within the tolerance.

Examples

Let's consider a practical scenario where these comparison operators come into play: comparing user input against predefined values.

#include <iostream>
using namespace std;

int main() {
    int secretNumber = 42;
    int userGuess;

    cout << "Guess the secret number: ";
    cin >> userGuess;

    if (userGuess == secretNumber) {
        cout << "Congratulations! You guessed it right." << endl;
    } else {
        cout << "Oops! That's not the secret number." << endl;
    }

    return 0;
}

The above code defines a simple guessing game. It initializes a secretNumber with the value 42, prompts the user to input their userGuess, and then uses an if statement to compare (using the == operator) the user's guess with the secret number. If the guess matches the secret number, it prints a congratulatory message; otherwise, it displays an error message indicating an incorrect guess.

Let's take another example to see how you can use these comparison operators in C++.

#include <iostream>
using namespace std;

int main() {
    int num1 = 10;
    int num2 = 20;

    // Equal to
    if (num1 == num2) {
        cout << "num1 is equal to num2" << endl;
    } else {
        cout << "num1 is not equal to num2" << endl;
    }

    // Greater than
    if (num1 > num2) {
        cout << "num1 is greater than num2" << endl;
    } else {
        cout << "num1 is not greater than num2" << endl;
    }

    // Less than or equal to
    if (num1 <= num2) {
        cout << "num1 is less than or equal to num2" << endl;
    } else {
        cout << "num1 is neither less than nor equal to num2" << endl;
    }

    return 0;
}

Here's the output of the above code,

num1 is not equal to num2
num1 is not greater than num2
num1 is less than or equal to num2

Conclusion

Comparison operators play a pivotal role in C++ programming, allowing developers to make decisions based on the relationship between values. Whether you're comparing numbers, characters, or even complex data structures, understanding how these operators work is crucial. With the knowledge of comparison operators, you can confidently utilize these operators to enhance the logic and functionality of your C++ programs.

9 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo