Search code examples
verilogsystem-verilogtest-bench

How to use variables in a loop with consecutive numbers in their names?


As mentioned in the question, i want to use variables in a loop with consecutive numbers in their names, the code is as follows:

`define VAR(idx) a_``idx
`define VAR_STR(idx) $psprintf("ENV_PATH.a_%0d", idx)

initial begin
    int a_0;
    int a_1;
    int a_2;
    int sum;
    
    for(int i=0; i<3; i++) begin
        //Method 1:No doubt it's wrong
        sum = sum + `VAR(i);
        
        //Method 2: Negative, uvm_hdl_read can't access env path
        int tmp_val;
        uvm_hdl_read(`VAR_STR(i), tmp_val)
        sum = sum + tmp_val;       
    end
end

So, is there a way to achieve the above requirement? Or is this even possible?

I have tried both of the above methods.


Solution

  • Method 1 never works because macros get expanded into text as your code gets compiled, not as they are procedurally executed. `VAR(i) gets expanded to a_i, and a_i was never declared.

    Method 2 should have worked if the path is correct and you have provided VPI access to the path.