module m();
function void fun(string data);
int len=data.len;
bit [255:0]real_data[];
real_data=new[len];
foreach(data[i])
begin
real_data[i]=real '(data[i]);//---------------marked -----------
$display("converted value of the data[%d]:%b",i,data[i]);
end
foreach(real_data[j])
begin
$write(":%e",real_data[j]);
end
endfunction
initial begin
fun("123");
#10;
fun("abc");
#10;
fun("2e3");
end
endmodule
//I want to write a function which can convert any string to real values. I am getting error at the ‘marked’ line. It says index is out of array dimension bounds. $write doesn’t execute saying ‘array is empty’.
Please help how to fix it.
This code is not legal and should have been caught as an error. You’ve declared len as a static variable and it would only get initialized once before time 0.
Hi
I have edited the question again. I have mentioned some delays between each function call so that there is no problem with the len declared as static. Let me know your thoughts.
Please go over Dave’s first answer and the link he has posted there.
Why do you think the delays would make any difference ? It’s not about delays or when the function is called. It’s about how you are “initializing” a function variable.
Let’s break your code to something simpler to make it easier to understand. Most modern simulators will give you an error or warning here.
module m();
function void fun(int b);
int a = b ; // This line isn't touched every-time the function is called. It's just "initialized".
$display("a is %0d",a);
endfunction
initial begin
fun(1); // a will be 0. it's initialized to 0, and never touched again.
#10;
fun(2); // a will still be 0
#10;
fun(3); // a will continue to be 0.
end
endmodule
Instead of the above, if you try the below, where to separate the initialization and the assignment, you will be fine. One of the ways to get want you want below::
module m();
function void fun(int b);
int a ;
a = b;
$display("a is %0d",a);
endfunction
initial begin
fun(1);
#10;
fun(2);
#10;
fun(3);
end
endmodule