1

I am looking at a function that says it returns two uints, but the return statement is inside an else statement, so obviously there are conditions under which nothing would be returned. Can you have conditional returns in solidity?

1 Answer 1

1

In Solidity, a function that returns a value doesn't need to do so explicitly.

For example take the following two functions:

function sometimes(uint x) public pure returns(uint y) {
        if(x == 7) {
            y =  7;
        }
    }

function never(uint x) public pure returns(uint y) {
        if(x == 7) {

        }
    }

sometimes() will return 0, the default value for uint, if you don't pass it the number 7, however if you do pass it 7, it will return 7.

never() will return the default value for uint regardless of the input passed to it.

Same thing with these remaining functions:

function sometimesBool(uint x) public pure returns(bool y) {
        if(x == 7) {
            y = true;
        }
    }

    function neverBool(uint x) public pure returns(bool y) {
        if(x == 7) {

        }
    }

    function sometimesString(uint x) public pure returns(string memory y) {
        if(x == 7) {
            y  = "7";
        }
    }

    function neverString(uint x) public pure returns(string memory y) {
        if(x == 7) {

        }
    }

sometimesBool() and sometimesString() will return true and 7 respectively when passed a 7.

neverBool() and neverString() will always return false and an empty string.

Some slight differences exist between these though, such as only the never() functions having a compiler warning:

Warning: Unused function parameter. Remove or comment out the variable name to silence this warning.

And if you were to declare your functions without naming the return variable, you would also get warnings for the sometimes() functions:

function sometimes(uint x) public pure returns(uint) {
        if(x == 7) {
            return 7;
        }
    }

Returns this error:

Warning: Unnamed return variable can remain unassigned. Add an explicit return with value to all non-reverting code paths or name the variable.

Related Ethereum issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.