Pointers in Verilog

Verilog supports pointers in a limited way through the use of references. We’ll demonstrate this concept using two modules: zeroval and zeroptr.

module zeroval(
    input wire [31:0] ival,
    output reg [31:0] oval
);
    always @(*) begin
        oval = 0;
    end
endmodule

module zeroptr(
    input wire [31:0] iptr,
    output reg [31:0] optr
);
    always @(*) begin
        optr = 0;
    end
endmodule

module main;
    reg [31:0] i;
    wire [31:0] zeroval_out, zeroptr_out;

    zeroval zeroval_inst(
        .ival(i),
        .oval(zeroval_out)
    );

    zeroptr zeroptr_inst(
        .iptr(i),
        .optr(zeroptr_out)
    );

    initial begin
        i = 1;
        $display("initial: %d", i);

        zeroval_inst.ival = i;
        #1; // Wait for combinational logic to settle
        $display("zeroval: %d", i);

        zeroptr_inst.iptr = i;
        #1; // Wait for combinational logic to settle
        i = zeroptr_out;
        $display("zeroptr: %d", i);

        $display("reference: %h", i);
    end
endmodule

In Verilog, we don’t have direct pointers like in software languages. Instead, we use wire and reg types to represent data, and modules to encapsulate functionality.

The zeroval module takes an input ival and always outputs 0. This is similar to the zeroval function in the original example, but it doesn’t modify the input directly.

The zeroptr module is similar, but it’s meant to represent the concept of modifying a value through a reference. In Verilog, this is achieved by outputting the new value and then assigning it back in the main module.

In the main module, we instantiate both zeroval and zeroptr. We then demonstrate their usage:

  1. We set i to 1 and display its initial value.
  2. We pass i to zeroval, but this doesn’t change i in the main module.
  3. We pass i to zeroptr, and then assign the output back to i, effectively changing its value.
  4. Finally, we display the “reference” (which in Verilog is just the value itself in hexadecimal format).

To run this Verilog code, you would typically use a Verilog simulator. The output might look something like this:

initial: 1
zeroval: 1
zeroptr: 0
reference: 00000000

Note that in Verilog, we don’t have the same concept of memory addresses as in software languages. The “reference” display is just showing the final value of i in hexadecimal format.