Ternary Operators in Solidity
A ternary operator or conditional operator in solidity is an operator that takes three operands. Ternary operators come in handy if the programmer wants to write a simple if-else statement in a single line.
Syntax 1: Ternary Operator
condition ? statement 1 : statement 2;
If the condition is true then execute statement 1, else execute statement 2.
Syntax 2: Ternary Operator Chaining
(condition 1) ? statement 1 : ( (condition 2) ? statement 2 : statement 3) ;
Using Ternary Operator in Solidity
Below is the Solidity program to implement the ternary operator:
Solidity
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.6 <0.9.0; /// @title A contract for demonstrate the Solidity Operator /// @notice For now, this contract just show how to implement Ternary Operator contract SolidityTest { constructor() {} function getResult() public pure returns (string memory) { // This code returns a string // if a > b we return "a is bigger" // else we return "b is bigger" uint256 a = 100; uint256 b = 200; return (a > b ? "a is bigger" : "b is bigger" ); } } |
Explanation: In the above code, we find the bigger of the two numbers a and b. If a > b we return a string “a is bigger” else we return the string “b is bigger” Here the condition of the ternary operator is a>b, statement 1 is “a is bigger” and statement 2 is “b is bigger”.
Output:
Chaining Ternary Operator in Solidity
The ternary operator can also be chained to check if a and b are equal this time. Below is the Solidity program to implement the above approach:
Solidity
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.6 <0.9.0; // @title A contract for demonstrate the Solidity Operator // @notice For now, this contract just show how to // implement Ternary Operator chaining contract SolidityTest { constructor() {} function getResult() public pure returns (string memory) { // This code returns a string // if a > b we return "a is bigger" // else if a == b we return "a and b are equal" // else b > a we return "b is bigger" uint256 a = 100; uint256 b = 100; return (a > b ? "a is bigger" : ( (a==b) ? "a and b are equal" : "b is bigger" ) ); } } |
Explanation:
- condition 1 is a>b and condition 2 is a==b
- statement 1 is “a is bigger”, statement 2 is “a and b are equal” and statement 3 is “b is bigger”
Output:
Contact Us