I'm learning Delphi myself.. I have seen the auto
variable type that can do some degree of magic in C++. Is there an auto
a variable type, or something similar to this, in Delphi?

- 555,201
- 31
- 458
- 770

- 1,082
- 2
- 17
- 37
-
4In Delphi 10.3 and later, you can simply write `var a := RHS`; the type of `a` will be the type of the right-hand side. – Andreas Rejbrand Mar 31 '22 at 13:30
-
4With that said, the use cases for `var` in Delphi are not as extensive [as those for C++](https://stackoverflow.com/q/6434971/327083) - prefer using explicit types unless you have a **very** compelling reason not to. – J... Mar 31 '22 at 14:17
-
https://www.embarcadero.com/resources/white-papers – Delphi Coder Mar 31 '22 at 15:55
1 Answers
auto
in C++ is used to let the compiler infer a variable's data type based on what type of value is used to initialize it.
In Delphi 10.3 and later, type inference is available only on an inline variable:
Additionally, the compiler can now in several circumstances infer the type of a variable at its inline declaration location, by looking to the type of the value assigned to it.
procedure Test; begin var I := 22; ShowMessage (I.ToString); end;
The type of the r-value expression (that is, what comes after the
:=
) is analyzed to determine the type of the variable. Some of the data types are “expanded” to a larger type, as in the case above where the numeric value 22 (aShortInt
) is expanded toInteger
. As a general rule, if the right hand expression type is an integral type and smaller than 32 bits, the variable will be declared as a 32-bitInteger
. You can use an explicit type if you want a specific, smaller, numeric type.

- 555,201
- 31
- 458
- 770