This section explains how to write the ternary operator in Solidity.
Syntax
Here is how the ternary operator is written in Solidity.
condition ? value if condition is true : value if condition is false
Sample Code
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract Test {
function showIsAdult(uint age) public pure returns(string memory) {
string memory attribute = age >= 20 ? "an adult" : "a minor"; // ternary operator
return string(abi.encodePacked("You are ", attribute, "."));
}
}
The ternary operator in Solidity is the same as in other programming languages.