Ternary Operator in Solidity

Published by Mario Oettler on

The ternary operator (?:) is a conditional assignment that exists in solidity and other programming languages. It has the following structure:

targetVar = condition ? result_if_true : result_if_false;

If the condition is true, the value result_if_true is assigned to the variable targetVar. If the condition evaluates to false, the result_if_false is assigned to targetVar.

It can be used instead of an if-else-statement.

The ternary operator can be more complex in order to assign multiple values at the same time.

(targetVar1, targetVar2) = condition ? (result_1_if_true, result_2_if_true) : (result_1_if_false, result_2_if_false);

Ternary Operator with Function Calls

The ternary operator in Solidity can also deal with function calls as a return value. Instead of simply returning a value, it can call a function that returns a value. As a source code example it would look like this:

pragma solidity 0.8.20;

contract TernaryTest{

    function callMeOnTrue() internal pure returns(uint256 res){
        return 42;
    }

    function ternaryTest(uint256 b) public pure returns(uint256){
        uint256 a = (b == 0)? callMeOnTrue() : 20;
        return a;
    }
}
Categories: