Skip to main content

Ignored Return Value

Description

In Solidity, it is important to handle return values properly to prevent unexpected behaviors. Ignoring a return value from a function that is expected to return a value can lead to serious issues. It can result in incorrect data being used in subsequent operations, leading to incorrect or even insecure behavior.

Example Code

Consider the following example code:

function doSomething() public {
uint256 result = someFunction();
// Ignoring the return value from someFunction()
}

function someFunction() public returns (uint256) {
// Do some calculation
return someValue;
}

In this code, doSomething() calls someFunction(), which returns a value of type uint256. However, the return value is not assigned to a variable and is therefore ignored. This can lead to issues if the returned value is expected to be used in subsequent operations.

Recommendation

To prevent issues related to ignored return values, it is important to always handle the return values of functions that are expected to return a value. Depending on the situation, there are several ways to handle return values:

  • If the return value is not needed, it can be discarded by assigning it to the special variable _.
  • If the return value is needed but not critical, it can be checked and logged to prevent unexpected behaviors.
  • If the return value is critical, it should be checked and handled appropriately. If the return value indicates an error or unexpected behavior, the contract should revert or take other appropriate action.

In the example code above, doSomething() should assign the return value of someFunction() to a variable, even if the value is not needed. This can be done by assigning the return value to the special variable _, like so:

function doSomething() public {
uint256 _ = someFunction();
// The return value is now assigned to the special variable `_`
}

Alternatively, if the return value is needed but not critical, it can be checked and logged to prevent unexpected behaviors:

function doSomething() public {
uint256 result = someFunction();
require(result > 0, "someFunction returned an unexpected value");
// Log the return value for debugging purposes
emit SomeEvent(result);
}

In summary, it is important to always handle return values properly to prevent issues related to ignored return values.