IIf

Last updated

In computing, IIf (an abbreviation for Immediate if [1] ) is a function in several editions of the Visual Basic programming language and ColdFusion Markup Language (CFML), and on spreadsheets that returns the second or third parameter based on the evaluation of the first parameter. It is an example of a conditional expression, which is similar to a conditional statement.

Contents

Syntax

The syntax of the IIf function is as follows:

IIf(expr, truepart, falsepart)

All three parameters are required:

Many languages have an operator to accomplish the same purpose, generally referred to as a conditional operator (or, less precisely, as a ternary operator); the best known is ?:, as used in C, C++, and related languages. Some of the problems with the IIf function, as discussed later, do not exist with a conditional operator, because the language is free to examine the type and delay evaluation of the operands, as opposed to simply passing them to a library function.

Examples

These examples evaluate mathematical expressions and return one of two strings depending on the outcome.

result = IIf(5 < 10, "Yes it is", "No it isn't")     ' Returns "Yes it is"
result = IIf(2 + 2 = 5, "Correct", "Wrong")          ' Returns "Wrong"

Criticisms

Efficiency

Because IIf is a library function, it will always require the overhead of a function call, whereas a conditional operator will more likely produce inline code.

Furthermore, the data type of its arguments is Variant. If the function is called with arguments of other types (variables or literals), there will be additional overhead to convert these to Variant. There may also be additional overhead to check the argument types and convert one of them if they do not have the same type.

Side effects

Another issue with IIf arises because it is a library function: unlike the C-derived conditional operator, both truepart and the falsepart will be evaluated regardless of which one is actually returned. In the following code snippet:

value=10result=IIf(value=10,''TrueFunction'', FalseFunction)

although TrueFunction is the function intended to be called, IIf will call both TrueFunction and FalseFunction. Similarly,

a=10b=0result=IIf(b<>0,a/b,0)

While the intent may be to avoid a division by zero, whenever b is zero the error will actually happen. This is because the code in the snippet is executed as if by

a=10b=0_temp1=b<>0_temp2=a/b' Error if b = 0_temp3=0If_temp1Thenresult=_temp2Elseresult=_temp3EndIf

This issue makes the IIf() call less useful than the conditional operator. To solve this issue, Microsoft developers had considered [2] converting IIf to an intrinsic function; had this happened, the compiler would have been able to perform type inference and short-circuiting by replacing the function call with inline code.

Alternatives to IIf

In Visual Basic, IIf is not the sole way to evaluate and perform actions based on whether an expression is true or false.

The following example uses IIf:

result = IIf(x = y, value1, value2)

It could also be written in the following way, using standard conditionals:

Ifx=yThenresult=value1Elseresult=value2EndIf

The above example would also eliminate the problem of IIf evaluating both its truepart and falsepart parameters.

Visual Basic 2008 (VB 9.0) introduced a true conditional operator, called simply "If", which also eliminates this problem. Its syntax is similar to the IIf function's syntax:

result=If(x=y,value1,value2)

IIf in other programming languages

$iif() is present in mIRC script, with similar syntax.

alias testiif {    %testiif = 0   echo -a $iif(1,$testiif2,$testiif2) %testiif execution(s)   unset %testiif } alias testiif2 { inc %testiif | return testing $!iif: } 

Calling /testiif will print out "testing $iif: 1 execution(s)". mIRC's $iif acts more like C's ?: than IIf() in VB since it won't pre-evaluate both.

IIF() is a function in dBase and xBase (1992 and older).

iif() is also a compiler magic function of Oxygene. It is not a real function and is at compile time unrolled to conditional statements.

varsomeString:=iif(someInt>35,'Large','Small');

In this example a new strong type string named "someString" is created (using Type inference) and the iif function will fill it depending on the outcome of the boolean expression.

SQL Server 2012 and newer implements the IIF() function (Transact-SQL):

DECLARE@aint=45;DECLARE@bint=40;SELECTIIF(@a>@b,'TRUE','FALSE')ASResult;

IIf in C (and its variants) and Perl is the ?: conditional operator:

printf("number %d is%s even",num,num%2?" not":"");

IIf in Python:

parity="odd"ifn%2else"even"

IIf (either) in Red and Rebol:

parity:eitherodd?n['odd]['even]

Related Research Articles

In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an expression until its value is needed and which also avoids repeated evaluations.

In logic, mathematics, and computer science, arity is the number of arguments or operands taken by a function, operation or relation. In mathematics, arity may also be called rank, but this word can have many other meanings. In logic and philosophy, arity may also be called adicity and degree. In linguistics, it is usually named valency.

In mathematics and computer science, a higher-order function (HOF) is a function that does at least one of the following:

In computer programming, a parameter or a formal argument is a special kind of variable used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are the values of the arguments with which the subroutine is going to be called/invoked. An ordered list of parameters is usually included in the definition of a subroutine, so that, each time the subroutine is called, its arguments for that call are evaluated, and the resulting values can be assigned to the corresponding parameters.

In computer programming, an assignment statement sets and/or re-sets the value stored in the storage location(s) denoted by a variable name; in other words, it copies a value into the variable. In most imperative programming languages, the assignment statement is a fundamental construct.

<span class="mw-page-title-main">C syntax</span> Set of rules defining correctly structured programs

The syntax of the C programming language is the set of rules governing writing of software in C. It is designed to allow for programs that are extremely terse, have a close relationship with the resulting object code, and yet provide relatively high-level data abstraction. C was the first widely successful high-level language for portable operating-system development.

<span class="mw-page-title-main">Conditional (computer programming)</span> Control flow statement that executes code according to some condition(s)

In computer science, conditionals are programming language commands for handling decisions. Specifically, conditionals perform different computations or actions depending on whether a programmer-defined Boolean condition evaluates to true or false. In terms of control flow, the decision is always achieved by selectively altering the control flow based on some condition . Although dynamic dispatch is not usually classified as a conditional construct, it is another way to select between alternatives at runtime. Conditional statements are the checkpoints in the programe that determines behaviour according to situation.

In computer programming, the ternary conditional operator is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, ternary if, or inline if. An expression a ? b : c evaluates to b if the value of a is true, and otherwise to c. One can read it aloud as "if a then b otherwise c". The form a ? b : c is by far and large the most common, but alternative syntaxes do exist; for example, Raku uses the syntax a ?? b !! c to avoid confusion with the infix operators ? and !, whereas in Visual Basic .NET, it instead takes the form If(a, b, c).

Short-circuit evaluation, minimal evaluation, or McCarthy evaluation is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true.

In computer programming, operators are constructs defined within programming languages which behave generally like functions, but which differ syntactically or semantically.

The computer programming languages C and Pascal have similar times of origin, influences, and purposes. Both were used to design their own compilers early in their lifetimes. The original Pascal definition appeared in 1969 and a first compiler in 1970. The first version of C appeared in 1972.

<span class="mw-page-title-main">Null (SQL)</span> Marker used in SQL databases to indicate a value does not exist

In SQL, null or NULL is a special marker used to indicate that a data value does not exist in the database. Introduced by the creator of the relational database model, E. F. Codd, SQL null serves to fulfil the requirement that all true relational database management systems (RDBMS) support a representation of "missing information and inapplicable information". Codd also introduced the use of the lowercase Greek omega (ω) symbol to represent null in database theory. In SQL, NULL is a reserved word used to identify this marker.

<span class="mw-page-title-main">JavaScript syntax</span> Set of rules defining correctly structured programs

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.

The conditional operator is supported in many programming languages. This term usually refers to ?: as in C, C++, C#, and JavaScript. However, in Java, this term can also refer to && and ||.

In computer programming, an anonymous function is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfil the same role for the function type as literals do for other data types.

The null coalescing operator is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, including C#, PowerShell as of version 7.0.0, Perl as of version 5.10, Swift, and PHP 7.0.0. While its behavior differs between implementations, the null coalescing operator generally returns the result of its left-most operand if it exists and is not null, and otherwise returns the right-most operand. This behavior allows a default value to be defined for cases where a more specific value is not available.

OpenHMPP - programming standard for heterogeneous computing. Based on a set of compiler directives, standard is a programming model designed to handle hardware accelerators without the complexity associated with GPU programming. This approach based on directives has been implemented because they enable a loose relationship between an application code and the use of a hardware accelerator (HWA).

The structure of the Perl programming language encompasses both the syntactical rules of the language and the general ways in which programs are organized. Perl's design philosophy is expressed in the commonly cited motto "there's more than one way to do it". As a multi-paradigm, dynamically typed language, Perl allows a great degree of flexibility in program design. Perl also encourages modularization; this has been attributed to the component-based design structure of its Unix roots, and is responsible for the size of the CPAN archive, a community-maintained repository of more than 100,000 modules.

In certain computer programming languages, the Elvis operator, often written ?:, is a binary operator that returns its first operand if that operand evaluates to a true value, and otherwise evaluates and returns its second operand. This is identical to a short-circuit or with "last value" semantics. The notation of the Elvis operator was inspired by the ternary conditional operator, ? :, since the Elvis operator expression A ?: B is approximately equivalent to the ternary conditional A ? A : B.

<span class="mw-page-title-main">Nim (programming language)</span> Programming language

Nim is a general-purpose, multi-paradigm, statically typed, compiled high-level systems programming language, designed and developed by a team around Andreas Rumpf. Nim is designed to be "efficient, expressive, and elegant", supporting metaprogramming, functional, message passing, procedural, and object-oriented programming styles by providing several features such as compile time code generation, algebraic data types, a foreign function interface (FFI) with C, C++, Objective-C, and JavaScript, and supporting compiling to those same languages as intermediate representations.

References

  1. "How to Use the IIf() (Immediate If) Function". 2004-06-08. Retrieved 2007-05-09.
  2. Paul Vick (2006-12-29). "IIF, a True Ternary Operator and Backwards Compatibility" . Retrieved 2007-02-01.