Return values let a function send back a result after it finishes. This helps you use that result later in your program.
0
0
Return values in Blockchain / Solidity
Introduction
When you want to get the outcome of a calculation from a function.
When you need to pass data from one part of your blockchain code to another.
When you want to check if a transaction was successful and get its details.
When you want to reuse a function's result without repeating the work.
Syntax
Blockchain / Solidity
function functionName(parameters) returns (returnType) {
// code
return value;
}The
returns keyword specifies the type of value the function will send back.Use
return inside the function to send the value back.Examples
This function returns the balance of the current contract as an unsigned integer.
Blockchain / Solidity
function getBalance() public view returns (uint) {
return address(this).balance;
}This function adds two numbers and returns the result.
Blockchain / Solidity
function add(uint a, uint b) public pure returns (uint) {
return a + b;
}This function returns a fixed string.
Blockchain / Solidity
function getName() public pure returns (string memory) {
return "Blockchain";
}Sample Program
This contract has a function multiply that returns the product of two numbers. The testMultiply function calls multiply and returns a string showing the result.
Blockchain / Solidity
pragma solidity ^0.8.0; contract SimpleCalculator { function multiply(uint x, uint y) public pure returns (uint) { return x * y; } function testMultiply() public pure returns (string memory) { uint result = multiply(3, 4); return string(abi.encodePacked("3 times 4 is ", uint2str(result))); } function uint2str(uint _i) internal pure returns (string memory str) { if (_i == 0) { return "0"; } uint j = _i; uint length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint k = length; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bstr[k] = bytes1(temp); _i /= 10; } str = string(bstr); } }
OutputSuccess
Important Notes
Functions can return only one value or multiple values using tuples.
Remember to match the return type in the function signature with the actual returned value.
In blockchain smart contracts, returning values helps verify results without changing the blockchain state.
Summary
Return values let functions send results back to where they were called.
Use returns to specify the type and return to send the value.
Return values help reuse results and check outcomes in blockchain code.