Pointers in Modelica

In Modelica, there is no direct equivalent to pointers. However, we can demonstrate similar concepts using pass-by-reference for objects and arrays. Here’s an example that illustrates these concepts:

model Pointers
  function zeroval
    input Integer ival;
    output Integer result;
  algorithm
    result := 0;
  end zeroval;

  function zeroref
    input output Integer iref;
  algorithm
    iref := 0;
  end zeroref;

  Real i;
equation
  when initial() then
    i = 1;
    Modelica.Utilities.Streams.print("initial: " + String(i));

    i = zeroval(integer(i));
    Modelica.Utilities.Streams.print("zeroval: " + String(i));

    zeroref(i);
    Modelica.Utilities.Streams.print("zeroref: " + String(i));
  end when;
end Pointers;

In this example, we demonstrate the difference between pass-by-value and pass-by-reference in Modelica.

The zeroval function takes an Integer input and returns a new value. This is similar to pass-by-value in other languages. The function doesn’t modify the original variable.

The zeroref function takes an input output parameter, which is Modelica’s way of passing by reference. Changes made to this parameter inside the function will affect the original variable.

In the equation section, we use an initial() event to trigger our operations:

  1. We initialize i to 1 and print its value.
  2. We call zeroval with i. This doesn’t change the original i.
  3. We call zeroref with i. This changes the value of i to 0.

Note that Modelica doesn’t have a concept of memory addresses or pointers like some other languages. Instead, it uses references for complex types like objects and arrays, which are always passed by reference.

When you simulate this model, you should see output similar to this:

initial: 1
zeroval: 1
zeroref: 0

This demonstrates that zeroval doesn’t change the original value, while zeroref does modify it.

In Modelica, the concept of “pointers” is abstracted away, and the language handles references internally. This approach helps to avoid common pointer-related errors while still allowing for efficient data manipulation.