Question

Is it possible to change the parameter calling behavior (in line 25) from left to right instead of right to left?

The code at the bottom prints 3 2 1 to the console.

with Ada.Containers.Vectors;
with Ada.Text_IO;

procedure Main is

   package Vector is new Ada.Containers.Vectors (Positive, Integer);
   V : Vector.Vector;

   procedure A (X, Y, Z : Integer) is
   begin
      Ada.Text_IO.Put_Line (X'Img & Y'Img & Z'Img);
   end;

   function B return Integer is
      X : Integer := V.First_Element;
   begin
      V.Delete_First;
      return X;
   end;

begin
   V.Append (1);
   V.Append (2);
   V.Append (3);
   A (B, B, B);
end Main;
Was it helpful?

Solution

No. The Ada language (like other languages) says that the order of parameter evaluation is undefined. You can't count on other compilers, or even different versions of the same compiler, behaving the same way. Even the same compiler could behave differently if it is performing aggressive optimization; in doing so, it could rearrange the code, and since the compiler writers know that the language allows parameters to be evaluated in any order, they may take advantage of that permission when deciding how to rearrange their internal trees, for example.

Bottom line: If you want things in a certain order, you'll have to spell out the order. It's more readable, anyway, because the reader isn't left wondering what's going on.

begin
    V.Append (1);
    V.Append (2);
    V.Append (3);
    declare
        Result1 : Integer := B;
        Result2 : Integer := B;
        Result3 : Integer := B;
    begin
        A (Result1, Result2, Result3);
    end;
end Main;

Individual items in a declarative part are guaranteed to be evaluated in the order in which they appear.

Note that this does not solve the problem:

begin
    V.Append (1);
    V.Append (2);
    V.Append (3);
    declare
        type Three_Integers is array (1..3) of Integer;
        Results : Three_Integers := (B, B, B);  -- order is undefined!
    begin
        A (Results (1), Results (2), Results (3));
    end;
end Main;

because the language says that the array components may be evaluated in any order.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top