0

According to the Solidity documentation,

For almost all types, you cannot specify where they should be stored, because they are copied every time they are used.

I have played around with this in Remix trying to understand it with the following code. I would expect that by adding "storage" to the "inc" function, I could use it to change multiple global uints, but "storage" is reserved for structs and arrays.

I'm having trouble understanding the reasoning behind this - that this can't be done "because they are copied every time they are used". I take this to mean that every time a uint is used in a function, a copy is made to memory - and nothing can be done about that. But I can alter a global uint within a function by saying, for example, "number1 += 1", and this will save to the state. So, I don't understand why a copy must be made each time.

pragma solidity ^0.4.0;

contract C {
    uint public number1;
    uint public number2;

    function incOne() public view {
        inc(number1);
    }

    function incTwo() public view {
        inc(number2);
    }

    function inc(uint storage d) internal pure {
        d += 1;                                         
    }
}
2

uint and all other primitive types are value-type and not reference-type. So that means that the value of these variables are copied every time they are used.

structs and arrays are reference types, so you can specify the storage location and when you do it will point to the reference of the object passed in the function instead of having the value in memory.

The types where the so-called storage location is important are structs and arrays. If you e.g. pass such variables in function calls, their data is not copied if it can stay in memory or stay in storage. This means that you can modify their content in the called function and these modifications will still be visible in the caller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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