-
Notifications
You must be signed in to change notification settings - Fork 22
Eberon ternary operator
vladfolts edited this page May 8, 2016
·
4 revisions
Ternary operator can be used as a shortcut for the IF/ELSE statement.
condition ? a : b
condition is a boolean expression.
a and b are expressions to evaluate.
The operator returns a when condition is TRUE and b when condition is FALSE. Ternary operator has lowest priority.
PROCEDURE max(a, b: INTEGER): INTEGER;
VAR
result: INTEGER;
BEGIN
IF a > b THEN
result := a;
ELSE
result := b;
END;
RETURN result;
END;
This code above may be rewritten in much shorter and cleaner manner using ternary operator:
PROCEDURE max(a, b: INTEGER): INTEGER;
RETURN a > b ? a : b;
END;
Ternary operator supports Implicit Type Narrowing:
TYPE
Base = RECORD END;
Derived = RECORD (Base) derivedField: INTEGER END;
PROCEDURE p(VAR b: Base): INTEGER;
RETURN b IS Derived ? b.derivedField : 0
END;