Why do I get 0 in the terminal with this code?
reg y = 4'b1100;
initial begin
$display("y: %b", y);
end
However, if I explicitly define the range, I get the correct number: 1100
reg [3:0] y = 4'b1100;
initial begin
$display("y: %b", y);
end
2 Answers 2
reg y
That declares the y
signal as a 1-bit wide signal. When you omit the optional range specifier for a signal declaration, it gives you a 1-bit signal.
The assignment y = 4'b1100
, assigns the LSB of the literal number to y
. The LSB is 0, so y
is 0. You have a bit width mismatch in your assignment expression. The LHS (y
) is 1-bit, but the RHS (4'b1100
) is 4-bit. y
can only take on the 1-bit values 0 and 1. It can not take on a 4-bit value.
SystemVerilog has a static type system, but weakly typed when in comes to integral values.
A static type system means that the declaration data type of a variable is fixed at compile time and cannot change once execution begins. Your declaration of y
without a range means it is a 1-bit integral variable. This is in contrast to dynamic type variables whose type can be changed based on the type of the value being assigned to the variable.
A weak type system means it implicitly casts different type expressions without warnings. SystemVerilog will silently extend or truncate different width integral expressions. It truncates the 4-bit literal 4'b1100
to a 1-bit value by truncating the rightmost 3-bits.
Most of the singular types like integral and reals are weakly typed. The aggregate types like unpacked arrays and structs are strongly typed. They need explicit casts to go from one type to another.