_IIF
Jump to navigation
Jump to search
Navigation:
Main Page with Articles and Tutorials
Keyword Reference - Alphabetical
Keyword Reference - By usage
Report a broken link
The _IIF function is a conditional operator-like feature allowing conditional evaluations with short-circuiting behavior.
Syntax
- result = _IIF(expression, truePart, falsePart)
Parameters
- expression is a condition that evaluates to a logical value (true or false).
- truePart is the value or expression returned when expression evaluates to true.
- falsePart is the value or expression returned when expression evaluates to false.
Description
- The _IIF function provides a way to perform conditional evaluations, similar to the ternary operator in C (condition ? truePart : falsePart).
- It ensures short-circuiting, meaning only the relevant branch (truePart or falsePart) is evaluated based on the condition.
- Since only the truePart or falsePart is evaluated, it ensures optimal performance and avoids unnecessary computation, as any procedures involved in the skipped branch are not called, be aware of this behavior.
- The return type is determined by the type of truePart.
- Mixing STRING with other data types in truePart and falsePart is not allowed.
- It allows inline evaluations, improving readability, and reducing the need for verbose IF...THEN...ELSE structures.
- A compiler error is thrown if expression cannot be evaluated as a boolean.
Availability
Examples
- Example 1
- Basic conditional evaluation.
DIM userInput AS INTEGER DIM result AS STRING PRINT "Enter a number:" INPUT userInput result = _IIF(userInput MOD 2 = 0, "Even", "Odd") PRINT "The number is "; result |
Enter a number: 5 The number is Odd |
- Example 2
- Using numeric expressions.
DIM x AS INTEGER, y AS INTEGER DIM max AS INTEGER PRINT "Enter the first number:" INPUT x PRINT "Enter the second number:" INPUT y max = _IIF(x > y, x, y) PRINT "The larger number is: "; max |
Enter the first number: 10 Enter the second number: 20 The larger number is: 20 |
- Example 3
- Preventing unnecessary evaluation.
DIM a AS INTEGER, b AS SINGLE PRINT "Enter a non-zero number:" INPUT a b = _IIF(a <> 0, 100 / a, 0) ' Avoids division by zero when a = 0 PRINT "Result: "; b |
Enter a non-zero number: 0 Result: 0 |
See also