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?


1 Answer 1


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, 2017 at 5:43
  • yeah great of course :) Oct 16, 2017 at 5:44
  • I'll update the answer :) Oct 16, 2017 at 5:45
  • 1
    The order should actually be if ( usedAddresses[msg.sender]||values[msg.sender] ) ;) Oct 16, 2017 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.