gawk: Conditional Exp
1
1 6.3.4 Conditional Expressions
1 -----------------------------
1
1 A "conditional expression" is a special kind of expression that has
1 three operands. It allows you to use one expression's value to select
1 one of two other expressions. The conditional expression in 'awk' is
1 the same as in the C language, as shown here:
1
1 SELECTOR ? IF-TRUE-EXP : IF-FALSE-EXP
1
1 There are three subexpressions. The first, SELECTOR, is always computed
1 first. If it is "true" (not zero or not null), then IF-TRUE-EXP is
1 computed next, and its value becomes the value of the whole expression.
1 Otherwise, IF-FALSE-EXP is computed next, and its value becomes the
1 value of the whole expression. For example, the following expression
1 produces the absolute value of 'x':
1
1 x >= 0 ? x : -x
1
1 Each time the conditional expression is computed, only one of
1 IF-TRUE-EXP and IF-FALSE-EXP is used; the other is ignored. This is
1 important when the expressions have side effects. For example, this
1 conditional expression examines element 'i' of either array 'a' or array
1 'b', and increments 'i':
1
1 x == y ? a[i++] : b[i++]
1
1 This is guaranteed to increment 'i' exactly once, because each time only
1 one of the two increment expressions is executed and the other is not.
1 ⇒Arrays, for more information about arrays.
1
1 As a minor 'gawk' extension, a statement that uses '?:' can be
1 continued simply by putting a newline after either character. However,
1 putting a newline in front of either character does not work without
1 using backslash continuation (⇒Statements/Lines). If '--posix'
1 is specified (⇒Options), this extension is disabled.
1