[fpc-pascal] New feature: IfThen() intrinsic
Sven Barth
pascaldragon at googlemail.com
Sun Jan 31 15:43:06 CET 2016
Hello together!
I've finally come around to add a feature that many people have asked
for throughout the years: an inline if that works like the if-statement
in that it only evaluates that expression that is indeed returned.
After the discussion last year about the inline-if I've decided to add
it as an intrinsic function instead of an extension of the language.
Like all intrinsics it's part of the System unit and "declared" like this:
=== code begin ===
function IfThen(Condition: Boolean; ThenExpr, ElseExpr: type): type;
=== code end ===
Since it's declared in the System unit it won't interfere with the
IfThen()s that are declared in the Math unit or other units, so they'll
continue to work as before to avoid any surprises.
An important point to note is that in general the result type is
determined by the ThenExpr (there are a few usability exceptions
regarding strings and chars).
Examples:
=== code begin ===
function A: LongInt;
begin
A := 42;
end;
function B: LongInt;
B := 21;
end;
var
i, j: LongInt;
s: String;
begin
i := 42;
j ;= IfThen(i < 32, 48, 21);
j := IfThen(True, 23, 49); // compiler will warn of unreachable code
j := IfThen(False, 23, 49); // compiler will warn of unreachable code
j := IfThen(i < 32, A, B); // in this case only B will be executed
//j := IfThen(i < 32, 32, '123'); // this will fail if there's no
suitable conversion operator available
//s := IfThen(j < 32, #42, 'Foo'); // this will fail as a char is expected
s := IfThen(j < 32, #42, #3294); // this will work however and will
result in a WideChar
s := IfThen(j < 32, 'Hello World', 'Hello'#3294'World'); // this will
also work and will result in a WideString (and a warning as s is a
Short-/AnsiString)
end;
=== code end ===
If there are any combinations of types that should work, but do not,
please don't hesistate to report them at http://bugs.freepascal.org/
Regards,
Sven
More information about the fpc-pascal
mailing list