SystemVerilog enum cast

SystemVerilog enum casting

Assigning a variable to enum type is illegal, below example shows assigning variable to enum type.

Assigning variable to enum

module enum_datatype;
  //declaration
  typedef enum int { red=0, green=1, blue=4, yellow, white=6, black=9 } Colors;
  
  Colors color;
  
  initial begin
    color = 4;
    $display("Colors  ::  Value of %0s is \t= %0d",color.name(),color);
  end
endmodule

Simulator Output

Warning-[ENUMASSIGN] Illegal assignment to enum variable
testbench.sv, 11
enum_datatype, "color = 4;"
Only expressions of the enum type can be assigned to an enum variable.
The type int is incompatible with the enum 'Colors'
Expression: 4
Use the static cast operator to convert the expression to enum type.
Colors :: Value of blue is = 4

Click to execute on   

enum casting

In the above example we have seen that assigning variable to enum type is illegal, this can be overcome by using casting.

Below example shows using cast to assign variable to enum type.

module enum_datatype;
  //declaration
  typedef enum int { red=0, green=1, blue=4, yellow, white=6, black=9 } Colors;
  
  Colors color;
  
  initial begin
    $cast(color,4);
    $display("Colors  ::  Value of %0s is \t= %0d",color.name(),color);
  end
endmodule

Simulator Output

Colors :: Value of blue is = 4

Click to execute on