Last update August 31, 2021

Function Parameter Attributes



Difference (last change) (no other diffs, normal page display)

Changed: 61c61
func_two(a,b);
func_three(a,b);

Function Parameter Attributes

This page describes the usage of the in, out, inout, and scope attributes when applied to the parameters of a function definition.

in

The argument is preserved, such that when control returns to the caller, the argument as passed by the caller is unchanged. This is equivalent to declaring const scope. The variable can not be changed and can not escape the scope of the function.

out

The argument is always initialized automatically by the called function before its code is executed. Any changes to the argument by the called function are returned to the caller. The called function never gets to see the value of the argument as it was before the called function gets control. The argument must a RAM item and not a literal or temporary value.

inout

The argument is passed to the called function with the same value as set by the calling function. Any changes to the argument by the called function are returned to the caller. In other words, the called function can see what value was passed to it before changing it. The argument must a RAM item and not a literal or temporary value.

Examples

This demonstrates the in attribute.

  char[] a;
  int    b;

void func_one(in char[] X, in int Y) { X[0] = 'a'; // Fail X = "zxcvbnm"; // Fail Y = 3; // Fail return X; // Should fail, may not be fully implemented. }


This demonstrates the out attribute.
  void func_two(out char[] X, out int Y)
  {
      X = "zxcvbnm";  // Modifies the string reference.
      if (Y == 1)
        Y = 3; // never executed because Y is always zero on entry.
      else
        Y = 4; // Modifies the data.
  }

a = "qwerty"; b = 1; func_two(a,b); writefln("%s %d", a,b); // --: zxcvbnm 4

The parameters were initialized as before but this time, because they are out parameters, the called function is able to modify them. Note that the parameters are re-initialized by the compiler such that the values set by the caller are totally ignored.


This demonstrates the inout attribute.
  void func_three(inout char[] X, inout int Y)
  {
      X[0] = 'a';   // Modifies the string contents.
      X = "zxcvbnm";  // Modifies the string reference.
      if (Y == 1)
        Y = 3; // Modifies the data.
      else
        Y = 4; // Modifies the data.
  }

a = "qwerty"; b = 1; func_three(a,b);

writefln("%s %d", a,b); // --: zxcvbnm 3

The parameters were initialized as before but this time, because they are inout parameters, the called function is able to modify them. Also the parameters are not re-initialized by the compiler and the values set by the caller are visible to the called function.


FrontPage | News | TestPage | MessageBoard | Search | Contributors | Folders | Index | Help | Preferences | Edit

Edit text of this page (date of last change: August 31, 2021 1:09 (diff))