Functions and Visibility
Every Solidity function needs an explicit visibility, controlling who can call it, and a mutability annotation, telling the EVM (and gas estimators) whether it touches the blockchain's state at all.
contract Counter {
uint256 private count;
function increment() public {
count += 1; // modifies state, costs gas
}
function getCount() public view returns (uint256) {
return count; // only reads state, free to call
}
function double(uint256 n) public pure returns (uint256) {
return n * 2; // touches no state at all, purely computes
}
}
Visibility
| Modifier | Callable from |
|---|---|
public | Anyone, and from within the contract |
external | Only from outside the contract |
internal | This contract and contracts that inherit from it |
private | Only this exact contract |
Mutability
viewfunctions read state but never modify it, calling one from outside costs no gas.purefunctions don't even read state, they're a pure computation on their inputs, also free to call.- Functions with neither modify state, and always cost gas when called as a real transaction.
TIP
Marking a read-only function view isn't just documentation, the compiler enforces it, if you accidentally write to a state variable inside a function marked view, it simply won't compile.