Search code examples
verilogsystem-veriloghdl

Multiple assignments to function return value


In a SystemVerilog function, is it legal to do multiple assignments to the implicitly-declared return variable? See the following function for an example:

  localparam int Q=1,I=0;
  function logic [1:0][Q:I][15:0] Cast24to16(input logic [1:0][Q:I][23:0] din);
    foreach (Cast24to16[n,iq])
      Cast24to16[n][iq] = din[n][iq][23 -: 8];
  endfunction

The language reference manual, IEEE Std 1800-2017, sec 13.4.1 states:

Function return values can be specified in two ways, either by using a return statement or by assigning a value to the internal variable with the same name as the function.

This seems a little unclear as to whether you can assign multiple times, like in my example. Furthermore, the example from the LRM directly after this statement and also all other examples I can find online all show the implicit return value only being assigned once. This makes me feel a bit unsettled.


Solution

  • The LRM also says just before the section you quoted

    The function definition shall implicitly declare a variable, internal to the function, with the same name as the function.

    I think you can safely assume that if there is no explicit return statement, it effectively inserts an implicit return (var_function_name);

    Also, if you declare your function with a static lifetime (which is the implicit default lifetime in a module), that implicit return variable has a static lifetime as well. That means it retains its value from the last time you called the function regardless of whether you assign it or not.

    module top;
      
      function int countme;
        countme++;
      endfunction
      
      initial repeat (10) $display(countme());
    endmodule