3
\$\begingroup\$

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
toolic
10.8k11 gold badges31 silver badges35 bronze badges
asked May 28, 2023 at 11:57
\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

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.

answered May 28, 2023 at 12:02
\$\endgroup\$
0
3
\$\begingroup\$

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.

answered May 28, 2023 at 14:19
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.