What is the difference between a reg and a wire? When are we supposed to use reg and when are we supposed to use wire in a verilog module. I have also noticed sometimes that
As declared in here:
The most commonly used net is wire, so let’s use it to understand a net better.
Think about a wire from your household, it is something which connects two electrical components. Right? Now, tell me what will happen if I snap the wire? Connection will be lost (high impedance path 'bz). That’s exactly how a net is synthesized in hardware — connection between two gates enabling continuous assignment. Nets cannot can not store a value (except for trireg, which can have a capacitive state, where if you snap the connection, it will be stuck at last assigned value)
See this simple Verilog code using wire(net):
module net_example (
input wire a,
input wire b
);
wire net;
assign net = a ? 1'b1 : (b ? 1'b0 : 1'bx);
endmodule
Synthesized Hardware:
So, I hope it was easy to understand nets. Let’s look at the reg now. Let me start off by saying, declaring anything with type reg does not always mean that it will be synthesized as a register (storage element). Quoting from what Verilog LRM (2005) section 4.7 says about reg,
Because the reg holds a value between assignments, it can be used to model hardware registers. Edge-sensitive (i.e., flip-flops) and level sensitive (i.e., reset-set and transparent latches) storage elements can be modeled. A reg need not represent a hardware storage element because it can also be used to represent combinatorial logic.
Focus on the word “can” in the aforementioned text. Unlike net, reg is capable of holding a value hence making it eligible to store values. And, that is why, it “can” be used as a storage element. Let’s dig deep with some Verilog code.
Verilog code using reg for making storage element:
module net_reg (
input wire a,
input wire b
);
reg register;
always @(*) begin
if (a) register = 1'b1;
else if (b) register = 1'b0;
end
endmodule
Since, I did not code what should be the value of register when a == 0 and b == 0, therefore, register holds the previous value (see the red line I made for showing the feedback) making it a memory element.
Synthesized hardware:
If I just add a line to provide default value to register in the aforementioned code, I’ve provided a value to register for all the combinations of a and b. Therefore, no need to hold any value. So, even though I declared the register as reg, it will be synthesized as a wire and not a storage element.
module net_reg (
input wire a,
input wire b
);
reg register;
always @(*) begin
register = 1'b0;
if (a) register = 1'b1;
else if (b) register = 1'b0;
end
endmodule
Synthesized hardware: So, major takeaway from here is that a reg is not always synthesized as storage element.