1

The title is a little bit vague but I've seen this contract and tried it on remix:

pragma solidity ^0.4.24;

contract Tester {

  struct Account {
    uint256 balance; 
  }

  mapping (address => Account) public accounts;

  function addBalance() public payable {
    Account storage a = accounts[msg.sender];
    a.balance = a.balance + msg.value;

  }


}

What happens is the following: 1. I check the value in the mapping and it's 0 2. I execute the addBalance function sending 10 wei 3. I check the value in the mapping and I see it's 10

How is that possible ? I am not updating the mapping.

  • if you dont want to update the map do Account memory a = accounts[msg.sender]; – Majd TL Jun 4 at 16:10
2

This line:

Account storage a = accounts[msg.sender];

...declares a storage pointer, which points into the mapping. Therefore, any change you make to a is reflected in the mapping.

This is different to a normal "storage variable", which is just a variable that persists in the contract's state (as opposed to a local/memory variable, which does not).


Edit:

Can't immediately find anything useful in the documentation, but there's this, written by Rob: Storage Pointers in Solidity

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.