Functions and visibility
A function has a name, parameters, a visibility, a state mutability and a return type. Together these decide who can call it, whether it may change the chain, and what it gives back.
Visibility has four levels. public functions can be called from anywhere, including inside the contract. external functions can only be called from outside, which can save gas for large inputs. internal functions can be called from the contract and the contracts that inherit from it. private functions can only be called from the same contract.
State mutability tells readers and the compiler what a function does. A view function reads state but never writes it. A pure function neither reads nor writes state and depends only on its inputs. A function with neither keyword can change state, and it costs gas when called in a transaction.
Functions can return several values at once, and the return values can be named. Named returns are assigned like local variables, which keeps longer functions readable. Visibility only controls who can call the function; it does not hide data, because everything on a blockchain can be read.
Special functions handle unusual calls. A constructor runs once when the contract is deployed. A receive function accepts plain ETH transfers, and fallback runs when no function matches the call. You will use all of them in later modules.
contract Calculator { uint256 private total; function add(uint256 x) external { total += x; } function get() external view returns (uint256) { return total; } function double(uint256 x) public pure returns (uint256) { return x * 2; } function divide(uint256 a, uint256 b) public pure returns (uint256 quotient, uint256 remainder) { require(b != 0, "Divide by zero"); quotient = a / b; remainder = a % b; } function addTwice(uint256 x) external { _addInternal(x); _addInternal(x); } function _addInternal(uint256 x) internal { total += x; } }
Try it yourself
Add a pure function average(uint256 a, uint256 b) that returns their average. Then change double from public to external, call it from inside another function, and read the compiler error.
Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.