Monday, November 24, 2014

Learn System Verilog Through Examples - 2: Functions

Here is a small code snippet to understand how functions work in System Verilog. There are multiple ways of calling a function and we can even pass an entire array to the function and process it. Since it passed through reference, no need to do copy business once processing is done inside the function.


int g=100; //this is variable is global in scope with static life time

module test;
  int value1;
  int abc[10] = {0,1,2,3,4,5,6,7,8,9};
  int i;
 
  initial begin;
    f1(); //calls function with the default input value of 10 as per func definition
    f1(5);
   
    value1 = f2();
    $display("Returned value from Function f2 -- Global Value value1: %d",value1);
   
    //Discard the return value
    //Interested in printing or the sub calls from this function
    void'(f2());
   
    //Passing an array to the function
    f3(abc);
    
    foreach (abc[i])
      $display("After updating array abc from function Item: %d is %d",i,abc[i]);
   
    f3(abc);
   
  end
endmodule

function f1(int a=10);//another way of clear declaration is function void f1(int a=10)
  static int b;
  $display("From Function f1 -- This is a function printing passed input: %d",a);
  $display("From Function f1 -- Value of static variable b is %d",b);
  b++;
endfunction

function int f2();
  return (++g);
endfunction

//function has to be declared automatic for passing array through reference
function automatic void f3(ref int a[10]);
  static int i;
 
  $display("From Automatic function f3 - Value of static variable i is %d",i);
 
  i=0;
 
  foreach (a[i])
    begin
      $display("From Automatic function f3 array a at location: %d is %d",i,a[i]);
      a[i] = a[i]+1;
    end
  i = 10;

endfunction

No comments:

Post a Comment