Purely as an exercise at home, aimed to better understand some language basics, I tried to reimplement the Ord
function, but I came across a problem.
In fact, the existing Ord
function can accept arguments of a variety of different types (AnsiChar
, Char
, WideChar
, Enumeration
, Integer
, Int64
) and can return Integer or Int64.
I can't figure out how to declare multiple versions of the same function.
How should this be coded in Delphi?
The Ord function returns the ordinal value of a character or enumeration as a non-negative integer.
In delphi exist a function called Ord which Returns the ordinal value of an ordinal-type expression. for example you can retrieve the Ascii value for a char in this way. Ord('A') return 65. Ord('a') return 97.
It stands for "ordinal". The earliest use of ord that I remember was in Pascal. There, ord() returned the ordinal value of its argument. For characters this was defined as the ASCII code.
I can't figure out how to declare multiple versions of the same function.
It's called function overloading. Input parameters must be different for each version, return type doesn't matter. For example:
function Ord(X: Char): Integer; overload;
begin
// Whatever here
end;
function Ord(X: Integer): Integer; overload;
begin
// Something
end;
// etc.
Ord
cannot be coded in Delphi. Although you can use the overload
directive to write multiple functions with the same name, you cannot write the Ord
function that way because it works for an arbitrary number of argument types without needing multiple definitions. (No matter how many Ord
overloads you write, I can always come up with a type that your functions won't accept but that the compiler's will.)
It works that way because of compiler magic. The compiler knows about Ord
and about all ordinal types in the program, so it performs the function's actions in-line. Other compiler-magic functions include Length
(magic because it accepts arbitrary array types), Str
(magic because it accepts width and precision modifiers), and ReadLn
(magic because it accepts an arbitrary number of parameters).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With