Search code examples
verilogsystem-verilog

What would right value of B and C from this code?


class A;
    function int foo();
        int a;
        return ++a;
    endfunction
  
endclass

program tb;
    A a =new;
    int b, c;

    initial begin
        for (int i = 0; i < 10; i++) begin
            b = a.foo();
            c = foo(); // Calls a different foo() outside of the class A
            $display("B = %0d", b);
            $display("C = %0d", c);
        end
    end

    function int foo();
        int a;
        return ++a;
    endfunction
endprogram

I ran this on the online EDA playground, and it printed out this result. Isn't both a's getting initialised every time the function foo (both the functions) is called ?

B = 1
C = 1
B = 1
C = 2
B = 1
C = 3
B = 1
C = 4
B = 1
C = 5
B = 1
C = 6
B = 1
C = 7
B = 1
C = 8
B = 1
C = 9
B = 1
C = 10
$finish at simulation time                    0
           V C S   S i m u l a t i o n   R e p o r t

Can someone explain how the value of C is incremented here?


Solution

  • The class foo function is an automatic function.

    The program foo function is a static function.

    This difference causes the difference in behavior of the 2 functions.

    The int a; line implicitly initializes a to 0. In the automatic function, this initialization happens every time the function is called. In the static function, this initialization only happens the first time the function is called. That is why C increments.

    In the program, if you explicitly declare the function as automatic, it will behave like the function in the class. Change:

    function int foo();
    

    to:

    function automatic int foo();
    

    Output:

    B = 1
    C = 1
    B = 1
    C = 1
    B = 1
    C = 1
    B = 1
    C = 1
    B = 1
    C = 1
    B = 1
    C = 1
    B = 1
    C = 1
    B = 1
    C = 1
    B = 1
    C = 1
    B = 1
    C = 1
    

    Refer to IEEE Std 1800-2017, section 13.4.2 Static and automatic functions

    Functions defined within a module, interface, program, or package default to being static, with all declared items being statically allocated.

    Functions defined within a class are always automatic