Using Absolute Keyword in Delphi to Remove Unnecessary Assignment Function


The Delphi/Object Pascal provides a keyword absolute, which you can also find examples at this post.. Basically, the keyword absolute allows you to specify the alias of a variable.

In C/C++, you use union to declare two variables that share the same memory location. For example,

1
2
3
4
union data {
  int a;
  float b;
} udata;
union data {
  int a;
  float b;
} udata;

That will give you a four byte size type data. You can either use udata.a or udata.b to retrieve the data in different format (both four bytes). Every variable type in union starts at the same location.

In Delphi/Object Pascal, the absolute does similar jobs.

var
  a: integer;
  b: single absolute a;

This says that the float variable b starts at the same location of the integer variable a.

Remove Unnecessary Assignment

For example, if you have a vector type, defined as follows:

type
  vector = array [0 .. 2] of Single;

And, you want to make a type using a function:

function makeVector(x, y, z: Single): vector; inline;
begin
  Result[0] := x;
  Result[1] := y;
  Result[2] := z;
end;

And, you want to use it this way:

var
  x, y, z: Single;
begin
  x := 1; y := 2; z := 3;
  passVector(makeVector(x, y, z));
end;

Well, with keyword absolute, this is not necessary anymore.

var
  x, y, z: Single;
  xyz: vector absolute x;
begin
  x := 1; y := 2; z := 3;
  passVector(xyz);
end;

We make variable xyz the alias of the three independent variables. Every time you change variable x, y and z, it reflects immediately to the vector variable xyz. This works because the three variables are stored continuously 4 byte each in memory so is variable xyz.

However, if you call makeVector this will actually return a separate copy of (x, y, z).

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
398 words
Last Post: How to Create a WordPress Page that Shows Comment Statistics?
Next Post: List of WordPress Plugins

The Permanent URL is: Using Absolute Keyword in Delphi to Remove Unnecessary Assignment Function

4 Comments

  1. Phil B

Leave a Reply