6

Consider the following contract in Solidity:

pragma solidity ^0.4.2;

contract Registry {
    struct Name {
        string first;
        string last;
    }

    mapping(address => Name) reg;

    function newName(string first, string last) {
        address sender = msg.sender;

        if(reg[sender] != 0) {
            throw;
        }

        reg[sender].first = first;
        reg[sender].last = last;
    }
}

In the if statement above, which is incorrect, I would like to check whether the struct Name is defined, or is still in the default value with all fields initialized to zero. Is there a language operator to do it?

eth
  • 85,679
  • 53
  • 285
  • 406

3 Answers3

8

I would go with:

if (reg[sender].first != "" || reg[sender].last != "") {
    throw;
}
5

There's no operator but you can check the length of both strings against zero:

if (bytes(reg[sender].first).length != 0 || bytes(reg[sender].last).length != 0) { throw; }

Note: use of ||

Related:

eth
  • 85,679
  • 53
  • 285
  • 406
2

To update this Answer to the latest version of Solidity. try the following: require(reg[sender].first && reg[sender].last);

Cyberience
  • 405
  • 3
  • 10