0

In Solidity 0.8 and above, do we still need to explicit define where parameters of a function should be stored?

I have a seen a number of examples that show something like this:

function foo1(string[] memory name) public returns (bool) {
 //...
}

function foo2(string[] calldata name) internal pure returns (bool) {
 //...
}

function foo3(string[] storage name) external returns (bool) {
 //...
}

function foo4(string[] name) external returns (bool) {
 // Without defining the storage location to the param, it's works fine too!
}

Is defining the storage location to the parameters of functions still a necessary thing? Or will this be handled by Solidity? It seems like it will still work even if I don't define them.

As far I have read, there are certain types of functions (depending on its modifier) that Solidity will store the parameters at different places. So, I wonder since Solidity is going to do its own thing to the parameters, then what's the point of us still defining them in our code?

If it's still necessary, in what scenarios should I know that I would want to define the storage type for the parameters?

1

Prior to version 0.5.0 the data location could be omitted, and would default to different locations depending on the kind of variable, function type, etc., but all complex types must now give an explicit data location. - Solidity docs

If you can, try to use calldata as data location because it will avoid copies and also makes sure that the data cannot be modified. Arrays and structs with calldata data location can also be returned from functions, but it is not possible to allocate such types. Assignments between storage and memory (or from calldata) always create an independent copy.

Storage: is a key-value store.

Memory: is a byte-array, which hold the data in it until the execution of the function.

Check this answer for more info: Difference between Memory and Storage?

So its not necessarily needed for non complex types , but advised to ensure your function does precisely what you intend it to do and does not break due to these changes. It is still needed for complex types. See more here: https://docs.soliditylang.org/en/v0.5.10/miscellaneous.html#

2
  • Thank you! Your answer has helped me to understand better now. Just a quick clarification, you mentioned “calldata data location can also be returns from functions, but it is not possible to allocate such types”. I don’t understand the part about being “not possible to allocate such types”. By “allocating such types”, do u mean we cannot modify the values returned from functions with calldata?
    – xenon
    Aug 13 '21 at 10:24
  • Yes, it is already allocated. See this for some extra info: docs.soliditylang.org/en/v0.8.7/internals/… Aug 13 '21 at 11:17

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.