03 - Return42

Goal: Return the number 42 from Yul.

Return42.t.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.13;

import {Test, console} from "forge-std/Test.sol";
import {Return42} from "../src/Return42.sol";

contract Return42Test is Test {
    Return42 public c;

    function setUp() public {
        c = new Return42();
    }

    function test_Return42() public {
        uint256 r = c.main();
        assertEq(r, 42);
    }
}

Returning an integer uses the same mechanism as returning a bool, but with a different value. We store the 256-bit representation of 42 in memory, then return 32 bytes. The number 42 (0x2A in hex) will be padded to 32 bytes (meaning 42 in the lowest bits and zeros elsewhere).

Return42.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.13;

contract Return42 {

  function main() external pure returns (uint256) {
      assembly {
          // Store 42 at memory position 0
          mstore(0, 42)
          // Return 32 bytes from memory position 0 (the value 42)
          return(0, 32)
      }
  }
}

Explanation: We use mstore(0, 42) to place the value 42 at memory location 0. Then return(0, 32) sends the 32-byte value back. The receiving side will interpret those 32 bytes as a uint256 equal to 42.

Run test:

forge test --mp test/Return42.t.sol -vvvv

Last updated