2

Let's consider the following code:

pragma solidity ^0.4.18;

contract Test {
  enum EnumTest {
    Test0,
    Test1
  }

  struct StructTest {
    EnumTest Foo;
    uint256 Bar;
  }
}

Not taking into account struct tight packing, what is the size of the member Foo inside StructTest? Does it depend on the number of members in the enum EnumTest?

1

Yes, it depends on the number of members in the enum.

See the official documentation:

pragma solidity >=0.4.16 <0.6.0;

contract test {
    enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill }
    ActionChoices choice;
    ActionChoices constant defaultChoice = ActionChoices.GoStraight;

    function setGoStraight() public {
        choice = ActionChoices.GoStraight;
    }

    // Since enum types are not part of the ABI, the signature of "getChoice"
    // will automatically be changed to "getChoice() returns (uint8)"
    // for all matters external to Solidity. The integer type used is just
    // large enough to hold all enum values, i.e. if you have more than 256 values,
    // `uint16` will be used and so on.
    function getChoice() public view returns (ActionChoices) {
        return choice;
    }

    function getDefaultChoice() public pure returns (uint) {
        return uint(defaultChoice);
    }
}
  • 1
    Although that documentation doesn't address how the enum is stored in storage, my testing confirms that it mirrors the way the return type is handled. Up to 255 values seems to take up 8 bits of storage, and 256 values seems to take up 16 bits of storage. (I tested by putting other state variables next to the enum such that the last one would only fit if the enum was constrained to 8 bits.) – user19510 Sep 15 at 20:27
  • @smarx: Well, this dude stated "Not taking into account struct tight packing", which IMO implies that the question is in fact agnostic to whether or not the enum is inside a struct. – goodvibration Sep 16 at 4:52
  • The testing I did involved no structs. – user19510 Sep 16 at 4:59
  • I suppose that when "not taking into account ... packing", the enum always takes up 256 bits in storage. – user19510 Sep 16 at 5:01

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.