🎓 A1Learner
🔍
0 of 50 lessons completed

Solidity Comparison Operators

Comparison operators are symbols that compare two values and give a true or false answer. A function can return that answer directly, with no extra steps.

Greater than and less than return a bool

Each function below returns the result of one comparison. The comparison itself is the whole answer.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract GreaterLess {
    function isGreater(uint256 a, uint256 b) public returns (bool) {
        return a > b;
    }

    function isLess(uint256 a, uint256 b) public returns (bool) {
        return a < b;
    }
}

Equal to and not equal to compare for a match

The == operator checks for an exact match. The != operator checks that the values differ.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract EqualCheck {
    function isEqual(uint256 a, uint256 b) public returns (bool) {
        return a == b;
    }

    function isNotEqual(uint256 a, uint256 b) public returns (bool) {
        return a != b;
    }
}

At least and at most include the equal case

The >= and <= operators both give true when the two values are equal. That equal case is what makes them different from > and <.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract AtLeastAtMost {
    function isAtLeast(uint256 a, uint256 b) public returns (bool) {
        return a >= b;
    }

    function isAtMost(uint256 a, uint256 b) public returns (bool) {
        return a <= b;
    }
}

Example

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract QuizCheck {
    function isPass(uint256 score) public returns (bool) {
        return score >= 50;
    }

    function isPerfect(uint256 score) public returns (bool) {
        return score == 100;
    }

    function needsMorePractice(uint256 score) public returns (bool) {
        return score < 50;
    }
}

Key points

  • Bool: a bool is a value that is either true or false.
  • Greater than: the > operator gives true when the left value is bigger than the right value.
  • Less than: the < operator gives true when the left value is smaller than the right value.
  • Equal to: the == operator gives true when both values are exactly the same.
  • Not equal to: the != operator gives true when the two values are different.
  • At least: the >= operator gives true when the left value is bigger than or equal to the right value.

In this example, the contract holds three small checks about a quiz score. The isPass function returns score >= 50, so the boundary value 50 itself passes. The isPerfect function returns score == 100, and needsMorePractice returns score < 50.

Note

the <= operator works the other way and gives true when the left value is smaller than or equal to the right value.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Remix IDE

Exercise

A function returns a <= b. What does it give when a is 3 and b is 3?