- DelphiTools - https://www.delphitools.info -

if then (else) expressions

“if” expressions are now supported in DWScript SVN, those were introduced to Pascal by Oxygene [1] a couple years back, and are Pascal’s verbose version of the C ternary operator (?:).

For instance

var s := if (a<>0) then Sin(1/a) else 1;

being equivalent to

var s : Float;
if (a<>0) then
   s := Sin(1/a)
else s := 1;

This can allow to eliminate the need for some intermediate variables and repetitions.

However the DWScript version is a bit stricter than the Oxygene version in that it won’t automatically box incompatible values to “Object”, it it will also not introduce a nullable type on its own for the result. If the “else” alternative is not present, the value of the expressions will be that that of the type’s default, ie. both following lines would be equivalent:

var msg1 := "There are " + IntToStr(n) + " user" + (if (n>1) then "s" else "");
var msg2 := "There are " + IntToStr(n) + " user" + if (n>1) then "s";

(as a reminder DWScript accepts both ” and ‘ to define strings [2])