When to Use wire and reg in Verilog: Clear Guide
wire for signals driven by continuous assignments or module outputs, representing physical connections. Use reg for signals assigned inside procedural blocks like always, representing storage elements or variables.How It Works
Think of wire as a physical wire in a circuit that always carries a signal from one place to another. It cannot hold a value by itself; it just connects outputs to inputs continuously. For example, if you connect a light switch to a bulb, the wire carries the current directly when the switch is on.
On the other hand, reg is like a small box that can hold a value until you change it. It is used inside blocks of code that run step-by-step, like a memory or a variable in a program. This is useful when you want to remember a value or update it only at certain times, like pressing a button to store a number.
Example
wire connects inputs and outputs continuously, and reg stores a value updated on a clock edge.module example(input clk, input a, output b); wire w; reg r; assign w = a; // wire driven continuously by input a always @(posedge clk) begin r <= w; // reg updated on clock edge end assign b = r; // output driven by reg value endmodule
When to Use
Use wire when you want to connect signals that are driven by continuous assignments, module outputs, or gates. It is perfect for simple connections without memory.
Use reg inside always or initial blocks when you need to store values, create flip-flops, or model sequential logic that updates on events like clock edges.
For example, use wire to connect combinational logic like AND gates, and use reg to build counters, state machines, or registers that remember values over time.
Key Points
- wire is for continuous connections and cannot store values.
- reg can store values and is assigned inside procedural blocks.
- Use
wirefor combinational logic outputs. - Use
regfor sequential logic and variables updated on events. - Choosing correctly helps model hardware behavior accurately.