What are pure functions in Solidity?
In
If the pure function is doing any of the following, the compiler will consider them as reading state variables and will throw a warning:
- Reading state variables
- Accessing balance or address
- Invoking a function that is not pure
- Accessing a global variable, message, or block
- Using certain opcodes in inline assembly
If the pure function is doing any of the following, the compiler will consider them as modifying state variables and will throw a warning.
- Modifying or over-writing state variables
- Creating new contracts
- Invoking a function that is not pure or view
- Emitting events
- Using certain opcodes in inline assembly
- Using
selfdestruct - Using low-level function calls
- Sending Ether along with function calls
Pure functions are allowed to use the
revert()andrequire()functions.
Syntax
function <function-name>() <access-modifier> pure returns() {
// function body
}
Code
In the code snippet below, we will see how to create a pure function in Solidity.
pragma solidity ^0.5.0;contract Example {// creating a pure function// it returns sum of two numbers that are passed as parameterfunction getSum(uint number1, uint number2) public pure returns(uint) {uint sum = number1 + number2;return sum;}}
Explanation
- In line 3, we create a contract named
Example. - In line 6, we define a pure function named
getSum(). - In line 7, the
getSum()function accepts two parametersnumber1andnumber2, and calculates their sum. - In line 8, the function returns the sum.
Since the function getSum() doesn’t read or modify any state variables, it is considered a Pure function.