Solidity Parameters and Returns
Parameters are the named inputs a function receives when it is called. Each parameter has a type and a name, and a function can hand one value back as its return.
One function can take several types
register takes a number, a true-or-false value, and an address. It stores each parameter in its own variable.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract PlayerCard {
uint256 public playerId;
bool public isActive;
address public captain;
function register(uint256 id, bool active, address leader) public {
playerId = id;
isActive = active;
captain = leader;
}
}
A function can return one value
add takes two numbers as parameters. Its return statement hands back their sum.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract Adder {
function add(uint256 first, uint256 second) public returns (uint256) {
return first + second;
}
}
No parameters, one stored value back
savedScore takes no parameters at all. It returns the value already stored in score.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract ScoreKeeper {
uint256 public score;
function setScore(uint256 newScore) public {
score = newScore;
}
function savedScore() public returns (uint256) {
return score;
}
}
Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract MatchSetup {
uint256 public maxPlayers;
bool public ranked;
function configure(uint256 players, bool isRanked) public returns (uint256) {
maxPlayers = players;
ranked = isRanked;
return players;
}
function playerLimit() public returns (uint256) {
return maxPlayers;
}
}
Key points
- Parameter: a type and a name written inside the parentheses.
- Several parameters: list them in order with commas between them.
- Different types: one function can take numbers, true-or-false values, and addresses together.
- Return type: the returns part says what type comes back.
- Return statement: return sends one value back and ends the function.
- No parameters: empty parentheses mean the call sends no inputs.
In this example, configure takes two parameters of different types and stores both of them. It also returns the player count as its one return value. playerLimit takes no parameters and returns the stored player count.
Note
the caller must send the parameters in the order the function lists them.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
A function is written as readCode() with empty parentheses. What does that tell the caller?