RareSkills Solidity Interview Question #25 Answered: What is the difference between view and pure?

Faybian Byrd
Coinmonks
Published in
2 min readFeb 16, 2024

--

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:

Previous articles:

Disclosure: Some content may have been generated with the help of artificial intelligence.

--

--

Faybian Byrd
Coinmonks

Senior Software Engineer, Full Stack/Frontend @Opentensor Foundation | Graduate - Advanced Solidity Bootcamp @ RareSkills. | Certified Solidity Developer (CSD)