Solidity documentation states that

the default (location -ronme) for local variables is storage

I understand that this makes sense so that localVar = contractStorageVar will result in localVar pointing, and not copying, contractStorageVar.

I'm trying to figure out how this works. For example, as local variables go out of scope, does their storage clear up?

1 Answer 1


No, storage variables are not cleared when they go out of scope. In most cases, you shouldn't be declaring local storage variables regardless, and the compiler will give you a warning if you try to.

In most cases, if you want to use types like arrays locally, you should explicitly declare them as memory variables like:

bytes memory myVariable = "abcd";

Note that the storage of your contract is essentially unlimited, but writing to storage is extremely expensive. Clearing storage (i.e. setting a nonzero byte to zero) refunds some of the gas.

If you don't intend to use a variable outside of your current scope, there's generally no reason to write the variable to storage. Note that memory variables are passed by reference as well, not copied.

  • 1
    Thank you Tjaden. Is it correct, though, that any local variable, by default, is storage? If so, do you recommend setting all of them to zero before the function ends?
    – ronme
    Nov 3, 2016 at 2:52
  • 2
    Only arrays(including bytes and string)are stored in storage by default. Anything under 32 bytes is just kept on the stack. If you are setting things to zero when the function ends, you should be explicitly declaring them as memory variables, not using storage. Nov 3, 2016 at 3:41
  • 1
    "Clearing storage (i.e. setting a nonzero byte to zero) refunds some of the gas." --- important reminding!
    – Suge
    Dec 16, 2017 at 8:28
  • What if the declared local variable is pointing to an existing (contract level) storage variable; is it then OK to declare it as a storage variable? E.g. for getting and modifying an existing mapping. May 3, 2023 at 16:35

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.