How to get the number of elements in an enumerated type

With an enumerated type, as shown below, there is a good way to get the number of elements in an enumerated type enum_t:

type enum_t is (ALFA, BRAVO, CHARLIE);  -- Number of elements is 3

-- Don't work: length is not valid attribute for enum_t
constant ENUM_LENGTH : natural := enum_t'length;  -- illegal!

Based on David Konoets answer, this can be done like this:

constant ENUM_LENGTH : natural := enum_t'pos(enum_t'right) + 1;
+4
source share
1 answer

First find its POSitional value, then you can get VHDL to tell you what it is:

entity enum_length is
end entity;

architecture foo of enum_length is
    type enum_t is (ALFA, BRAVO, CHARLIE);
    constant enum_left:     natural := enum_t'POS(ALFA);
    constant enum_right:    natural := enum_t'POS(CHARLIE);
begin
    assert FALSE 
         Report "CHARLIE POS = " & natural'IMAGE(enum_right);
end architecture;

ghdl -r enum_length
enum_length.vhdl: 9: 5: @ 0ms: (assertion error): CHARLIE POS = 2

See IEEE Std 1076-2008 5.2.2.1 (Types of Enumerations) General, clause 6:

. . ; , .

, 0. . VAL :

entity enum_length is
end entity;

architecture foo of enum_length is
    type enum_t is (ALFA, BRAVO, CHARLIE);
    constant enum_left:     natural := enum_t'POS(ALFA);
    constant enum_right:    natural := enum_t'POS(CHARLIE);
    constant enum_t_elems:  natural:= enum_t'POS(enum_t'RIGHT) + 1;
begin
--    assert FALSE 
--        Report "CHARLIE POS = " & natural'IMAGE(enum_right);

    assert FALSE 
        Report "enum_t number of elements = " & natural'IMAGE(enum_t_elems);
end architecture;

ghdl -r enum_length
  enum_length.vhdl: 13: 5: @0ms: ( ): enum_t = 3

+3

All Articles