Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading