arrayssolidityremix-ide

Remix Solidity Array: Why modifying array does not return array value


// SPDX-License-Identifier: Unlicensed
pragma solidity >= 0.7.0;

contract Basic{
    
    uint[] public val  = [1,2];

    function demo() public  returns(uint) {
        val[0] = 22;
        return val[0];
    }

    function d2() public view returns(uint){
        return val[0];
    }
}

enter image description here

normally without modifying the array value it return in demo but after assignin 22 no return value is shown in demo funciton. if we modify can we not view in same function in solidity


Solution

  • Your function demo() doesn't have a view nor pure modifier, so the Remix IDE executes it by sending a transaction (read-write, costs gas fees).

    On the other hand, the function d2() uses a view modifier, so the IDE executes it by sending a (read-only, gas free) call.

    Only calls pass a value returned from the function outside of the EVM (or in this case - outside of the EVM emulator within the IDE).

    Possible workarounds:

    1. Emit an event log that you can read from the transaction receipt. In Remix IDE, transaction receipt opens up after you click the transaction line in the console.

      contract Basic{
      
          event DemoEvent(uint256);
      
          uint[] public val  = [1,2];
      
          function demo() public  returns(uint) {
              val[0] = 22;
              emit DemoEvent(val[0]);
          }
      }
      

      event log screenshot

    2. Two-step process. Update the value using the demo() function, and then read it using the autogenerated getter function for val.

      getter function screenshot