Statements and Operators: Comparison with the Less Than Operator

What is it?

The less than operator < in C++ is a comparison operator used to compare two values. It checks if the left operand is less than the right operand. If the left operand is less than the right operand, it returns true; otherwise, it returns false.


Syntax

The syntax of using the less than operator in C++ is as follows:

operand1 < operand2

Where,

  • operand1: The value or variable on the left-hand side of the operator.
  • operand2: The value or variable on the right-hand side of the operator.



How to use it

To use the less than operator, follow the below steps:

  1. Declare the variables you want to compare.
  2. Use the less than operator < between the two variables or values.
  3. The operator will return true if the left operand is less than the right operand, and false otherwise.



Program code snippet example

#include <iostream>

using namespace std;

int main() {

    int a = 10;
    int b = 20;

    // Comparing the variables a and b using less than operator.
    bool result = a < b;

    if (result) {
        cout << "a is less than b" << endl;
    } else {
        cout << "a is not less than b" << endl;
    }

    return 0;
}

Output:

a is less than b



Important to know

  • The less than operator can be used with integer, floating-point, and pointer values.
  • It cannot be used directly with class objects unless the class has overloaded this operator.
  • The operator returns a boolean value: true or false.



Best practices

When using the less than operator, it is important to keep the following best practices in mind:

  1. Use with appropriate types: The less than operator should only be used with numeric and pointer types, or classes that have overloaded this operator.

  2. Don't assume equality when the less than operator returns false: If a < b is false, it doesn't necessarily mean that a is equal to b. a could also be greater than b.

  3. Use parentheses for clarity: If you're using the less than operator in a complex expression, consider using parentheses to make the operation order clear.

  4. Check for null before comparing pointers: If you're using the less than operator with pointers, always check that they're not null before making the comparison.




Add a less than expression to a, b, and c to evaluate to true.