Returning Values
Part of the Fundamentals section of Coddy's Solidity journey. Lesson 22 of 53.
A function can compute a result without printing it. Declare the result type with returns, then use return inside the body. The caller can store the returned value and use it in a larger expression. Returning and printing are separate actions.
Define this helper inside the contract:
function doubled(uint256 n) internal pure returns (uint256) {
return n * 2;
}Use it inside the provided main function:
uint256 value = doubled(9);
console.log(value + 1);The helper returns eighteen. The caller adds one and prints nineteen. A return statement ends the current function call, so ordinary instructions after an unconditional return cannot contribute to that call.
A returned value can be stored or used by the caller without being printed by the helper.
Challenge
EasyWrite an internal pure helper named square that returns n times n. In main, store square(side) in a variable and print it.
The tests pass arguments to main in this order: uint256 side. Each test starts with fresh contract state.
Use console.log for the requested output. Print only the requested values, one per line, with no extra labels unless the task specifies them.
Try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import "forge-std/console.sol";
contract Main {
function main(uint256 side) external view {
// Write your solution here.
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
Practice on your own: Solidity playground