[fpc-pascal] New feature: IfThen() intrinsic

silvioprog silvioprog at gmail.com
Sun Jan 31 16:09:38 CET 2016


On Sun, Jan 31, 2016 at 11:43 AM, Sven Barth <pascaldragon at googlemail.com>
wrote:

> 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/
>

Wooow! I did a request about it many years ago, however it was rejected
because the limitation in the generic feature at that time.

So, I posted a bug related to it yesterday:

http://bugs.freepascal.org/view.php?id=29546

Can I use it after this new feature? (I'm upgrading my FPC sources now :-) )

Buddy, thanks a lot for that feature, it is very useful! o/

-- 
Silvio Cl├ęcio
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20160131/e315a3f1/attachment.html>


More information about the fpc-pascal mailing list