Solidity Fundamentals

Lesson 3 of 7

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

ModifierCallable from
publicAnyone, and from within the contract
externalOnly from outside the contract
internalThis contract and contracts that inherit from it
privateOnly this exact contract

Mutability

  • view functions read state but never modify it, calling one from outside costs no gas.
  • pure functions 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.

📝 Functions and Visibility Quiz

Passing score: 70%
  1. 1.Which function type touches no state at all, purely computing from its inputs?

  2. 2.Calling a view function from outside the contract (not as part of a state-changing transaction) costs no gas.

  3. 3.The visibility modifier that only allows a function to be called from outside the contract is: ____