What are pure functions in Solidity?

In SolidityAn object-oriented programming language, a function that doesn’t read or modify the variables of the state is called a pure function. It can only use local variables that are declared in the function and the arguments that are passed to the function to compute or return a value.

Simple illustration for pure functions

If the pure function is doing any of the following, the compiler will consider them as reading state variables and will throw a warning:

  1. Reading state variables
  2. Accessing balance or address
  3. Invoking a function that is not pure
  4. Accessing a global variable, message, or block
  5. 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.

  1. Modifying or over-writing state variables
  2. Creating new contracts
  3. Invoking a function that is not pure or view
  4. Emitting events
  5. Using certain opcodes in inline assembly
  6. Using selfdestruct
  7. Using low-level function calls
  8. Sending Ether along with function calls

Pure functions are allowed to use the revert() and require() 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 parameter
function 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 parameters number1 and number2, 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.