0
0
Blockchain / Solidityprogramming~5 mins

View and pure functions in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

View and pure functions let you read or calculate data without changing anything on the blockchain. They help save costs and keep things safe.

When you want to check a value stored on the blockchain without changing it.
When you need to calculate something based on inputs but don’t want to save the result.
When you want to show information to users without making a transaction.
When you want to avoid paying gas fees for simple data retrieval.
When you want to keep your contract’s state unchanged during a function call.
Syntax
Blockchain / Solidity
function functionName() public view returns (type) {
    // code that reads state but does not modify it
}

function functionName() public pure returns (type) {
    // code that neither reads nor modifies state
}

view

pure

Examples
This view function reads the stored data without changing it.
Blockchain / Solidity
uint storedData;

function getData() public view returns (uint) {
    return storedData;
}
This pure function adds two numbers without reading or changing any stored data.
Blockchain / Solidity
function add(uint a, uint b) public pure returns (uint) {
    return a + b;
}
Sample Program

This contract has a view function to get a stored number and a pure function to add two numbers without touching the stored data.

Blockchain / Solidity
pragma solidity ^0.8.0;

contract Example {
    uint storedNumber = 10;

    // View function: reads storedNumber
    function getStoredNumber() public view returns (uint) {
        return storedNumber;
    }

    // Pure function: adds two numbers without reading state
    function addNumbers(uint a, uint b) public pure returns (uint) {
        return a + b;
    }
}
OutputSuccess
Important Notes

Calling view and pure functions from outside the blockchain does not cost gas.

Trying to modify state inside a view or pure function will cause an error.

Use pure when your function only uses inputs and does not read blockchain data.

Summary

View functions read blockchain data but do not change it.

Pure functions neither read nor change blockchain data; they only use inputs.

Both help save gas and keep your contract safe when you only need to read or calculate data.