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) —
loading...
Last Post: How to Create a WordPress Page that Shows Comment Statistics?
Next Post: List of WordPress Plugins
Example does not work if x,y,z are declared as local variables. The memory of xyz[0] IS tied to x, but setting y, z does not change xyz[1], xyz[2] values or vice versa.
It seems to me that the compiler does not necessarily allocate the local vars in contiguous memory space.
For the global variable case, I guess it is safe to assume that this ‘trick’ will work in the future since SysUtils FormatSettings uses the same thing… however, it is also marked as deprecated by Delphi and shouldn’t be relied on in my opinion.
“absolute” is low level and should not be used unless you want to do some low-level hacking.
This is a great article mate 🙂
Glad this is helpful to you.