1

Though in the latest solidity compiler versions, it has been made clear that for reference variables local to a function, one needs to now explicitly mention its location modifier (memory, storage), thereby removing the whole confusion about its default nature.

But it is still unclear where are all the local variables defined as uint, uint8, bool, address, enum etc. of a function stored ? is it stored in storage, memory or stack ?

1

The primitive scalar types:

  • bool
  • uint
  • address
  • etc.

reside in storage when declared globally, and in memory when declared in functions.

contract Locations {

  // storage
  bool switch;
  uint number;
  address account;

  function doSomething() public pure {
    // memory
    bool switch2;
    uint number2;
    address account2;
  }
}

Hope it helps.

  • do we have any credible source citing this, or mentioned in the solidity documentation somewhere ? I've heard from some sources that some local primitive data types may be even stored in stack. – Kombo Nov 25 '18 at 18:02
  • 1
    I don't think it's possible to explicitly reference values in the stack outside of assembly. All operations use the stack so we are implicitly putting values onto it and taking them off of it all the time, but this is hidden from us through the use of Solidity. All declared variables are either in memory, storage or calldata (I believe calldata is only specified for arguments in external function calls, msg.data is also referred to as calldata). – willjgriff Nov 29 '18 at 17:53
2

Variables can be stored in 3 ways in solidity: storage, memory, and stack.

Storage: Storage is where all the contract state variables reside. Every contract has its own storage and it is persistent between function calls and quite expensive to use.

Memory: Memory is cheaper to use as it stores values temporarily. It is erased between external function calls. Memory is not persistent.

Stack: Almost free to use. Stack can be used to hold small local variables, but only limited in number.

Complex variable types, which don't always fit into 256 bits have to be handled carefully. For example, arrays and structs have an additional annotation, called 'data location' that indicates where it is stored in memory or storage.

So, you can use the following concept:

Forced data location:

  • parameters (not return) of external functions: calldata

  • state variables: storage

Default data location:

  • parameters (also return) of functions: memory

  • all other local variables: storage

Also, take a look at: Storage and Memory - Solidity Docs

  • it doesn't clarify where the primitive data types are stored. – Kombo Nov 25 '18 at 14:37

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.