Function arguments not initializing variable inside the body

Not sure why the following code is not working. (Pasted below)
=================FAILING=============================================

module test;

  function int divide(int dividend, int divisor);
    int i = dividend / divisor;
    return i;
  endfunction

  initial begin
    int j;
    j =divide(200,  64);
    $display("j=%0d", j);
  end
endmodule

On running with vcs or ncverilog I get the following output “j=0”.

If I change the code as below then I get the correct answer “j=3”.
============PASSING=====================================

 function int divide(int dividend, int divisor);
    int i;
    i  = dividend / divisor;    // MOVED TO NEW LINE
    return i;
  endfunction

In reply to sanjeevs:
Your failing code is illegal according to the SystemVerilog 1800-2012 LRM. (see 6.21 Scope and lifetime). Your simulator should have generated an error.

You are not allowed to have an initialization on a variable whose lifetime is implicitly static and has the option to be declared automatic. This is because unlike most programming languages, the default lifetime of variables in a function is static, and initialization of static variables happens before time 0, not when calling the function. In your example, you are expecting i to behave as an automatic. So you need to do one of the following

  • explicitly declare i automatic
  • declare the function automatic, which makes variable declared inside it implicitly automatic
  • declare the module automatic, which makes functions declared inside it implicitly automatic
  • split the declaration and initialization so that the initialization happens when the function gets called.

Also see When should be program block dynamic or static ? members of static program block , members of automatic program blocks ? | Verification Academy

In reply to dave_59:

Hi Dave,

I had a question. Agreed we need to declare the function as Automatic. But, for this simple example if the code was modified to this below. this would still work right. For cerain applications like Recursion, etc then yes the Function has to be declare Automatic if it is inside a module.

function int divide(int dividend, int divisor);
    int i;
    i  = dividend / divisor;    // MOVED TO NEW LINE
    return i;
  endfunction

In reply to sriram.seshagiri:

You wrote what seems to be a statement, not a question.
But I believe your statement is correct as the original question author said, it was passing (correctly) when written that way.