RareSkills Solidity Interview Question #25 Answered: What is the difference between view and pure?
This series will provide answers to the list of Solidity interview questions that were published by RareSkills..
Question #25 (Easy): What is the difference between view and pure?
Answer: 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.
Demonstration:
// 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;
}
*/
}
Further Discussion:
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.
Connect with me:
- Github: https://github.com/FaybianB
- LinkedIn: https://www.linkedin.com/in/faybianbyrd/
Previous articles:
- Question #15 (Easy): What is the difference between assert and require?
- Question #16 (Easy): What is a flash loan?
- Question #17 (Easy): What is the check-effects pattern?
- Question #18 (Easy): What is the minimum amount of Ether required to run a solo staking node?
- Question #19 (Easy): What is the difference between fallback and receive?
- Question #20 (Easy): What is reentrancy?
- Question #21 (Easy): As of the Shanghai upgrade, what is the gas limit per block?
- Question #22 (Easy): What prevents infinite loops from running forever?
- Question #23 (Easy): What is the difference between tx.origin and msg.sender?
- Question #24 (Easy): How do you send Ether to a contract that does not have payable functions, or a receive or fallback?
Disclosure: Some content may have been generated with the help of artificial intelligence.