Ternary Operator in Solidity

Published by Mario Oettler on

Last Updated on 12. June 2023 by Mario Oettler

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:

https://blockchain-academy.hs-mittweida.de/wp-content/uploads/2021/04/logo_bcam_rgb_gross.png

Welcome

Blockchain Academy

Continue with credential

No account yet?

Powered by Hidy

Register with Hidy


Register
Sign in

We need the following credential to register:

please select:

To create a new account, we need the following data from you:

We would appreciate the following additional information from you for the creation of your account:

Welcome

Blockchain Academy

Continue with credential

Already have an account?

Powered by Hidy

Sign in with Hidy


Register
Sign in

We need the following credential to log in:

please select: