solidity logo

Question: What are View Functions and Pure Functions in Solidity? Explain their use cases and differences.

View Functions
Definition:
In Solidity, a function marked as view indicates that it can read the blockchain state but cannot modify it. In other words, executing a view function will not change any storage variables in the contract.

Use Cases:

  • When you need to query contract state without altering it.
  • Examples include checking an account’s balance, verifying whether a user has specific permissions, etc.
  • Can be executed without spending gas when called off-chain (e.g., using a Web3 client).

Example:

pragma solidity ^0.8.0;

contract Coin {
    mapping(address => uint) balances;

    function getBalance(address _addr) public view returns (uint) {
        return balances[_addr];
    }
}

Pure Functions
Definition:
A function marked as pure indicates that it neither reads nor modifies the blockchain state. Pure functions depend entirely on their input parameters and do not interact with the contract’s state in any way.

Use Cases:

  • Ideal for mathematical calculations or string manipulations.
  • Suitable when you need logic that doesn’t involve the contract’s storage variables.
  • Can be executed without consuming gas, regardless of whether it is called on-chain or off-chain.

Example:

pragma solidity ^0.8.0;

contract Math {
    function add(uint a, uint b) public pure returns (uint) {
        return a + b;
    }
}

Key Differences

AspectView FunctionPure Function
State AccessCan read stateCannot read or modify state
State Modification❌ Not allowed❌ Not allowed
Gas Usage (off-chain)FreeFree
Gas Usage (on-chain transaction)May consume a small amountMay consume a small amount
Typical Use CaseQuerying contract stateCalculations / logic independent of state

Subscribe for New Articles!

Leave a Comment

Your email address will not be published. Required fields are marked *