Reputation: 187
I was wondering if system verilog has an ability to change the variable names on the fly. For example, I have the following code :
var1 = 1;
var2 = 2;
var3 = 3;
and I want to do the following checks
if(var1 == 1)
$display("var1 matched");
if(var2 == 2)
$display("var2 matched");
if(var3 == 3)
$display("var3 matched");
So in the above case, if I have 'n' variables, I'll have 'n' checks.
So for this reason, I was looking for an alternative way which works something like this :
for(int i=0; i<=3;i++)
if($sformatf("var%0d", i) == i) //here the variable name changes on the fly
$display("var%0d matched", i);
I tried the above code and there were no errors but it wasn't behaving as expected.
I also tried a string concatenation like so
for(int i=0; i<=3;i++)
if({var,$sformatf("%0d", i)} == i)
$display("var%0d matched", i);
Surprisingly this gave no errors too. But it was comparing i to i hence always passes.
Can someone tell me if there is anything in system verilog that I could use?
Thanks
Upvotes: 0
Views: 2226
Reputation: 16
Look in section 22.5.1 of the IEEE1800-2012 spec. You can use a macro with `` to construct identifiers from arguments.
`define dyn_var(x) var``x
for(int i=1; i<=3;i++)
if(`dyn_var(i) == i)
$display("var%0d matched", i);
Upvotes: 0
Reputation: 1373
I just checked the sections of the LRM that are related to this and could not find any reference indicating that it is supported. The behavior you are seeing is due to the fact that you are using the $sformatf function inside the "cond_predicate" expression of the conditional "if" statement.
Upvotes: 0