This series will provide answers to the list of Solidity interview questions that were published by RareSkills.
The difference between view
and pure
is that view
declares that a function can read from the blockchain but cannot modify the state of the contract, while pure
declares that a function cannot read from the blockchain or modify the state of the contract.
The view
modifier is used when the function needs to access or read state variables, access balances, or read from other functions or contracts that do not modify the state.
Usage: The pure
modifier is used for functions that perform calculations or operations solely based on the input parameters, without needing any data from the blockchain.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
contract ViewAndPureExamples {
uint storedData = 42;
// view function: reads state variable but does not modify it
function getStoredData() external view returns (uint) {
return storedData;
}
/**
* pure function: does not read or modify state, works only with input
* values
*/
function addNumbers(uint a, uint b) external pure returns (uint) {
return a + b;
}
/**
* Example showing the difference: trying to access a state variable in a
* pure function will result in a compilation error. Uncommenting the
* following function will demonstrate this
/*
function attemptToReadInPureFunction() external pure returns (uint) {
/**
* This line would cause a compilation error because you cannot read
* state in a pure function.
*/
// return storedData;
}
*/
}
Since view
and pure
functions do not make any state modifications, they do not consume any gas when called “off-chain”, such as from a web3 provider.