Pure functions in Solidity are functions that do not read or modify the state variables.
Pure functions do not read or modify state variables; instead, they return values that are derived solely from the parameters supplied to the function or from local variables that are contained in it. The compiler issues a warning in such circumstances if any of the statements that read the state variables, access the address or balance, access any global variable block or msg, call a function that is not pure, and so on, are present in pure functions.
Pure functions are those that do not read or modify the state of the system. It is possible to declare a function to be pure.
If any of the following statements are present in the function, they are regarded as reading the state, and the compiler will issue a warning in such circumstances:
State variables are being read.
-
Using the address(this).balance or
.balance functions. Using any of the special variables of block, tx, or msg (msg.sig and msg.data can be read).
Calling any function that has not been declared as pure.
Using inline assembly that contains specific opcodes.
If an error occurs, pure functions can utilise the reverse() and require() procedures to undo any potential state changes that may have occurred.
Example 1:
//SPDX-License-Identifier: MIT
pragma solidity ^0.5.0;
// Defining a contract
contract Test {
// Defining pure function to
// calculate product and sum
// of 2 numbers
function getResult(
) public pure returns(
uint product, uint sum){
uint num1 = 2;
uint num2 = 4;
product = num1 * num2;
sum = num1 + num2;
}
}
Example 2:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract ViewAndPure {
uint public x = 1;
// Promise not to modify the state.
function addToX(uint y) public view returns (uint) {
return x + y;
}
// Promise not to modify or read from the state.
function add(uint i, uint j) public pure returns (uint) {
return i + j;
}
}
For more content, follow me at - https://linktr.ee/shlokkumar2303
Top comments (0)