Value initialization with task input

Hi, I am assigning task input to task local variable during decleration(senario_1) and declaring a task variable and assigning a initalizing avalue in thr next line(scenario-2). I am getting different outputs for scenario-1 and scenario-2. can you please provide difference between scenario-1 and scenario-2


// Code your testbench here
// or browse Examples
module a;
   
  task fac1(input int i);
    begin
         //comment scenario-2 when running scenario-1
      reg[3:0] result=i; //scenario-1	
      result++;			//scenario-1
      
      //comment scenario-1 when running scenario-2
      
    //  reg[3:0] result;	//scenario-2
    //  result=i;			//scenario-2
    //  result++;		//scenario-2
      		
      
      
      $display("fac 3 result=%0d i=%0d",result,i);
     
    end
  endtask
  initial begin
   
    fac1(5);
    fac1(5);
    fac1(5); 
  end
endmodule

In reply to sh88:

Please use code tags making your code easier to read. I have added them for you.

Refer to section 13.3 of the LRM regarding static and automatic tasks, and how having an initializer for a variable changes its behavior.

In reply to cgales:

I have checked the lrm ,I didn’t understand, can you please explain in detail.

In reply to sh88:

A task declared within a module defaults to being static. This results in all items (variables) within the task also being static. In the first scenario, declaring the variable with an initialized variable results in the variable being initialized to its default value (0 in this case), and the initialization part is ignored (since it is part of the variable declaration statement). Each successive call results in ‘result’ being incremented from 0 to 1 to 2 etc.

In scenario 2, you assign the static variable ‘result’ with the input variable, hence it will have the value passed in each time it is called, and it will then subsequently be incremented. Each successive call will assign ‘result’ to the input value.

In reply to cgales:

The code you wrote for scenario-1 is actually illegal for the very reason it introduces a common misconception about tasks/functions with static lifetimes. See function arguments not initializing variable inside the body | Verification Academy