How can I know if a key is unset?

The Solidity documenation on Mappings says:

Mappings can be seen as hash tables which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros: a type’s default value.

If I'm mapping to an int, how can I differentiate between key with a value which is set to zero, vs key with an unset value which defaults to 0x0?


If I had to do this, I would use two mappings, one for the values and one to check whether if the address is used (keeping a flag - as @RobHitchens has suggested in a comment).

pragma solidity ^0.4.0;

contract Example {

    mapping(address => uint) public values;
    mapping(address => bool) public usedAddresses;

    function update(uint newVal) {

        values[msg.sender] = newVal;
        usedAddresses[msg.sender] = true;

    function dosomethiingwithval(){


             //do whatever with values[msg.sender]

  • 1
    Thanks! Wouldn't if(values[msg.sender] || usedAddresses[msg.sender]) save gas? – Tom Hale Oct 16 '17 at 5:43
  • yeah great of course :) – Achala Dissanayake Oct 16 '17 at 5:44
  • I'll update the answer :) – Achala Dissanayake Oct 16 '17 at 5:45
  • 1
    The order should actually be if ( usedAddresses[msg.sender]||values[msg.sender] ) ;) – Achala Dissanayake Oct 16 '17 at 5:47

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.