Verilog Crash Course code / reg_swap_nonblocking.v
Code Sample · Correct version

reg_swap_nonblocking.v

The correct half of the demo in Lesson 4 — Sequential Logic. Original source: code/reg_swap_nonblocking.v.

// Register swap using NON-BLOCKING assignment -- the correct way to
// swap two registers on a clock edge. See Lesson 4 (Sequential Logic).
//
// Both right-hand sides are captured using the values from BEFORE this
// edge (a=1, b=2), and both updates land together at the end of the
// time step, producing a genuine swap: a=2, b=1.
module reg_swap_nonblocking (
    input  wire clk,
    output reg  [7:0] a,
    output reg  [7:0] b
);

    initial begin
        a = 8'd1;
        b = 8'd2;
    end

    always @(posedge clk) begin
        a <= b;
        b <= a;
    end

endmodule

← Back to home  ·  ← See the buggy version