SystemVerilog Enum Examples¶
Declaring an enum¶
Here are a few examples from the SystemVerilog LRM of how to declare an enum
enum {red, yellow, green} light1, light2; // anonymous int type
enum {bronze=3, silver, gold} medal; // silver=4, gold=5
// c is automatically assigned the increment-value of 8
enum {a=3, b=7, c} alphabet;
// Defining a new data type as an enum
typedef enum logic [2:0] {
ETH,
IPV4,
IPV6,
UDP,
TCP,
ICMP,
VLAN,
RSVD
} pkt_hdr_e;
pkt_hdr_e pkt_hdr; // declare variable
Creating an enum range¶
SystemVerilog has a rarely used feature that can totally do this. Here’s how you would use it:
enum { REG[0:3]} regname_e;
Few more examples from the LRM
// Creates enums:
// add=10, sub0=11, sub1=12, sub13, jmp6, jmp7, jump8
typedef enum { add=10, sub[3], jmp[6:8] } E1;
// Creates enums:
// register0=1, register1=2, register2=10, register3=11, register4=12
enum { register[2] = 1, register[2:4] = 10 } vr;
Here’s a working example that you can test:
module test_enum;
typedef enum {
REG[0:7]
} regname_e;
initial begin
regname_e regname;
regname = REG1;
$display("regname is %s", regname.name());
regname = REG5;
$display("regname is %s", regname.name());
end
endmodule
Output
regname is REG1
regname is REG5
Printing an enum by name¶
While displaying messages, you can call the .name()
function on a variable of enum type to return the enum type as a string. You can also just use .name
without the braces.
module test_enum;
typedef enum {
REG0, REG1, REG2
} regname_e;
initial begin
regname_e regname;
regname = REG1;
$display("regname is %s", regname.name);
regname = REG2;
$display("regname is %s", regname.name());
end
endmodule
regname is REG1
regname is REG2