9

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;

  } 

}
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
aanchal jain
  • 91
  • 1
  • 3

2 Answers2

15
  • 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.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • _"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. – Nawaz Jan 25 '23 at 22:11
10

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.

Yakko Majuri
  • 448
  • 3
  • 13