Ternary Operators in Solidity
Last Updated :
19 Apr, 2023
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
pragma solidity >=0.8.6 <0.9.0;
contract SolidityTest {
constructor() {}
function getResult() public pure returns (string memory) {
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:
“b is bigger”
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
pragma solidity >=0.8.6 <0.9.0;
contract SolidityTest {
constructor() {}
function getResult() public pure returns (string memory) {
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:
“a and b are equal”
Share your thoughts in the comments
Please Login to comment...