Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ord function implementation in Delphi

Tags:

delphi

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?

like image 840
Federico Zancan Avatar asked Mar 27 '12 10:03

Federico Zancan


People also ask

What does the Ord function do in Delphi?

The Ord function returns the ordinal value of a character or enumeration as a non-negative integer.

What is Ord in C?

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.

What does ORD function stand for?

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.


2 Answers

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.
like image 93
Joonas Pulakka Avatar answered Sep 22 '22 09:09

Joonas Pulakka


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).

like image 39
Rob Kennedy Avatar answered Sep 21 '22 09:09

Rob Kennedy