Pure and View Functions in Solidity
Thanks to GrandZero
Aim: To learn pure and view functions
Code:https://github.com/veridelisi/basic-solidity/blob/main/pureandview/pureandview.sol
Pure Functions
Functions can be declared pure
in which case they promise not to read from or modify the state.(Source : SolidityLang)
It means that you cannot change state and you cannot read the state.
View Functions
Functions can be declared view
in which case they promise not to modify the state.(Source : SolidityLang)
It means that you can read the state but you cannot change the state
TypeError: Function declared as pure, but this expression (potentially) reads from the environment or state and thus requires “view”.
This is true version.
We try to change the state using view.
Function declared as view, but this expression (potentially) modifies the state.
This is true version.
Pure function only uses with local variables that are declared in the function.
Warning: Function state mutability can be restricted to pure
This is true version.
Question ? What do you use for the following functions?
uint public number = 7;
uint public number2=9;
function addWithState(uint y) public ……. returns (uint) {
return number + y;
}
function addWithoutState(uint i, uint j) public ….. returns (uint) {
return i + j;
}
Answer:
Why ?
You need to use view in the addWithState function because this function uses state variable (number)
You need to use pure in the addWithoutState function because this function doesnt use state variable (number). These are only local variables.
Dr.Engin YILMAZ
Ankara
2022