DEV Community

Cover image for View Functions in Solidity
Shlok Kumar
Shlok Kumar

Posted on

View Functions in Solidity

View functions are read-only functions that ensure state variables cannot be modified after calling them

The view functions are read-only functions, which ensures that state variables cannot be updated after they have been invoked by the user. The compiler will issue a warning if any of the following statements are found in view functions: modifying state variables, emitting events, creating other contracts, using the selfdestruct method, transferring ethers via calls, calling a function that is not 'view or pure', using low-level calls, and so on. The view function is used as the default get method.

View functions assure that they will not cause any changes to the current state. It is possible to declare a function as a view.

 If any of the following statements are included in the function, they are deemed to be changing the state, and the compiler will issue a warning in such circumstances:

  • Changing the values of state variables.

  • Emitting events.

  • Other contracts are being created.

  • Selfdestruct is being used.

  • Sending Ether over function calls.

  • Calling any function that is not designated as view or pure.

  • Making use of low-level calls.

  • Using inline assembly with specific opcodes to accomplish this.

Example 1:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

// Defining a contract
contract Test {

    // Declaring state 
    // variables
    uint num1 = 2; 
    uint num2 = 4;

   // Defining view function to  
   // calculate product and sum 
   // of 2 numbers
   function getResult(
   ) public view returns(
     uint product, uint sum){
       uint num1 = 10;
       uint num2 = 16;
      product = num1 * num2;
      sum = num1 + num2; 
   }
}
Enter fullscreen mode Exit fullscreen mode

 

Example 2:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract ViewAndPure {
    uint public x = 1;

    // Promise not to modify the state.
    function addToX(uint y) public view returns (uint) {
        return x + y;
    }
Enter fullscreen mode Exit fullscreen mode

For more content, follow me at - https://linktr.ee/shlokkumar2303

Top comments (0)