SHORT: What is the difference between PURE and VIEW modifiers in Solidity?

odutolaabisoye

Odutola Abisoye

Posted on June 24, 2022

SHORT: What is the difference between PURE and VIEW modifiers in Solidity?

Function modifiers

You want to create a function without actually changing the state in Solidity — e.g. it doesn’t change any values or write anything.


VIEW indicates that the function will not alter the storage state in any way but view only

PURE indicate that it will not read the storage state.


---

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract ViewAndPure {
    uint public x = 1;

    // Promise not to modify the state.
    function addToX(uint y) public view returns (uint) {
        return x + y;
    }

    // Promise not to modify or read from the state.
    function add(uint i, uint j) public pure returns (uint) {
        return i + j;
    }
}
Enter fullscreen mode Exit fullscreen mode

SUMMARY

VIEW A read-only function, which ensures that state variables cannot be modified after calling them. If the statements which modify state variables, emitting events, creating other contracts, using selfdestruct method, transferring ethers via calls, Calling a function which is not ‘view or pure’, using low-level calls, etc are present in view functions then the compiler throw a warning in such cases. By default, a get method is view function.

PURE The pure functions do not read or modify the state variables, which returns the values only using the parameters passed to the function or local variables present in it. If the statements which read the state variables, access the address or balance, accessing any global variable block or msg, calling a function which is not pure, etc are present in pure functions then the compiler throws a warning in such cases.

If you call view or pure functions externally, you do not pay a gas fee.

💖 💪 🙅 🚩
odutolaabisoye
Odutola Abisoye

Posted on June 24, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related