What is the difference between pure and view modifiers in solidity?
Asked Answered
A

2

10

The code results in same output.

pragma solidity ^0.5.0;
contract mycontract
{

   function add(uint c, uint d) public pure returns(uint)
  { uint e=c+d;


   return e;

  } 
   function add(uint j, uint k) public view returns(uint)
  { uint f=j+k;


   return f;

  } 

}
Asleyaslope answered 10/5, 2020 at 10:48 Comment(0)
D
17
  • view indicates that the function will not alter the storage state in any way. But it allows you to "view" it or read it

  • pure is even more strict, indicating that it will not even read the storage state.

    A pure function is a function which given the same input, always returns the same output. But the state of the contract keeps changing as users interact with it. So if you pass a state variable as an argument to the function, since the state is changing, that function will not be pure. That's why pure functions cannot access to state.

    "pure" functions are heavily used in mathematical libraries. For example SafeMath.sol

    Also inside pure functions, you cannot

    • use address(this).balance

    • call other functions except pure functions

if you call view or pure functions externally, you do not pay a gas fee. However, they do cost gas if called internally by another function.

Dias answered 23/10, 2021 at 2:18 Comment(1)
"if you call view or pure functions externally, you do not pay a gas fee." and then " However, they do cost gas if called internally by another function." ... What is the rationale for such a design? Sounds so complicated with ad-hocs rules, and probably stupid.Statant
B
12

pure does not view nor modify state. i.e. it can only use what is provided to it to run. view cannot modify state, but can look it up.

Bott answered 11/5, 2020 at 17:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.