Pure and view Functions
Sometimes, functions do not modify the state or read from it. In order to mark those functions, the keywords view and pure are used.
View
If a function is marked as view, it doesn’t modify the state but it can read from the state.
The following statements modify the state:
- Writing to state variables,
- emitting events,
- creating other contracts,
- sending Ether,
- calling functions that are not marked pure or view,
- using low-level-calls,
- invoking selfdestruct,
- certain opcodes from inline assembly.
Pure
If a function is marked pure, it neither reads from the state nor modifies it.
The following statements are considered as reading from the state:
- reading from state variables,
- accessing the balance of an address,
- accessing any of the members of block, tx, msg (except msg.sig and msg.data),
- calling any function that is not pure,
- certain opcodes from inline assembly.
Code Sample
The following code sample shows how to use pure and view.
pragma solidity 0.8.20;
contract pureAndview{
string greetings = "Hello World";
function myViewFunction() view public returns (string memory){
return greetings;
}
function myPureFunction(uint256 _a, uint256 _b) pure public returns (uint256){
return _a+ _b;
}
}