1

Since reference types such as arrays are passed by reference by in Solidity, they pass a reference (pointer) to the value. Any change to that value will reflect on original value.

If this is the case, why the changeVar() function does not change the value of marks array?

pragma solidity ^0.8.0;


contract ref {
     uint[] public marks  = [1,2,33];

    function changeVar() public {
        changeVal(marks);
    }

    function changeVal(uint[] memory _uint) public returns(uint[] memory){
            _uint[0] = 111;
    }

}

2 Answers 2

0

You added the memory modifier to the _uint argument. That means that whatever value you pass to the changeVal function, the array will be worked on in memory, not in storage.

So to answer your point, this is indeed a reference, but it's a reference to an array saved in memory. If you'd like to operate on and modify the storage array, you'd want to change the modifier to storage.

You may benefit from reading the Layout in Memory section of the Solidity docs.

4
  • Thanks but it gives error whenever I pass storage as an argument.
    – Emrah
    Mar 21, 2022 at 16:10
  • Whenever I pass storage as an argument, it says either calldata or memory needed but storage passed.
    – Emrah
    Mar 21, 2022 at 16:11
  • If my answer helped you, don't forget that you can click the thumbs up button, or mark it as accepted. Mar 21, 2022 at 16:25
  • I have responded my question. It took storage as an argument...
    – Emrah
    Mar 21, 2022 at 21:26
0
pragma solidity ^0.7.0; 

contract ref { 

uint[] public marks  = [1,2,33]; 

function changeVar() external { 
    changeVal(marks); 
} 

function changeVal(uint[] storage _uint) internal{ 
    _uint[0] = 111; 
    } 
}

The only way to pass the storage keyword to the function argument is if its type is internal or private. The functions will receive a copy when called by a regular user from another contract regardless of its type (reference or value). For other cases where pass by reference is used, see the examples.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.