4

What is the correct way to see if a bytesN value is of "default" value; whatever value is assigned to it upon declaration?

The following works, but seems unsafe:

contract Assertnil {
    bytes32 v;
    function test() constant returns (bool) {
        assert(v == "");
        return true;
    }
}

This seems more correct, but slightly more expensive:

contract Assertnil {
    bytes32 v;
    function test() constant returns (bool) {
        bytes32 w;
        assert(v == w);
        return true;
    }
}
3

There is no attribute or function asserting default value, only by comparison. Assembly is a good way and more cheaper, a simple demo as follows:

pragma solidity ^0.4.13;

contract test{

    bytes32 v ;

    function isEmpty() returns (bool flag){
        assembly {
            flag := eq(eq(sload(v_slot),0),1)
        }
    }
}

Hope it helps~

  • I tried that as is and it wouldn't compile, but when I move bytes32 v into the function and changed v_slot to v and tried solc --gas it came out more expensive than just testing v == "" – Edmund Edgar Aug 11 '17 at 14:09
  • Please tell me error log, i test everything is ok. If you move into function, generating variable will consume 183 gas, so more expensive. sload will cost more less because of loading from stack, not new. – BinGoBinBin Aug 11 '17 at 14:17
  • My bad, it's a version incompatibility. It breaks on the 0.4.16 nightly build: abltest.sol:9:33: Error: Identifier not found or not unique flag := eq(eq(sload(v_slot),0),1) but latest stable 0.4.15 is OK. However, I only get a saving of 3 gas vs == "" (398 vs 401) and the latter is better when using --optimize (368 vs 362). – Edmund Edgar Aug 11 '17 at 22:17

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.