Search code examples
verilogsystem-verilog

Foreach loop with string array


I want the code to be same as:

addr = `TX_B+'h00;
addr = `TX_B+'h04;
addr = `TX_B+'h08;
addr = `TX_B+'h0C;
addr = `TX_B+'h10;

by using foreach (or others that achieve same effect)
but it can't work. Is there any syntax error?

reg [5] TX_ADDR = {"00", "04", "08", "0C", "10"};
int i;

foreach (TX_ADDR[i])
begin
  addr = `TX_B + TX_ADDR[i];
end

Solution

  • Your declaration of TX_ADDR should have been a syntax error. The Cadence simulator gave me an error, but the Synopsys simulator did not. Try your code on different simulators on EDAPlayground.

    Here is some code which compiles cleanly and runs on both simulators:

    `define TX_B 1
    
    module tb;
    
    reg [7:0] TX_ADDR [5] = {'h00, 'h04, 'h08, 'h0C, 'h10};
    int i;
    int addr;
    
    initial begin
        foreach (TX_ADDR[i])
        begin
          addr = `TX_B + TX_ADDR[i];
          $display("addr=%0d", addr);
        end
    end
    
    endmodule
    

    Output:

    addr=1
    addr=5
    addr=9
    addr=13
    addr=17
    

    Since you did not post a complete code example, I made several assumptions. I doubt you really wanted string values for your array there, but if you really do, you need to convert them to numeric values to for the addition.