manpagez: man pages & more
info gawk
Home | html | info | man
File: gawk.info,  Node: Conditional Exp,  Prev: Boolean Ops,  Up: Truth Values and Conditions

6.3.4 Conditional Expressions
-----------------------------

A "conditional expression" is a special kind of expression that has
three operands.  It allows you to use one expression's value to select
one of two other expressions.  The conditional expression in 'awk' is
the same as in the C language, as shown here:

     SELECTOR ? IF-TRUE-EXP : IF-FALSE-EXP

There are three subexpressions.  The first, SELECTOR, is always computed
first.  If it is "true" (not zero or not null), then IF-TRUE-EXP is
computed next, and its value becomes the value of the whole expression.
Otherwise, IF-FALSE-EXP is computed next, and its value becomes the
value of the whole expression.  For example, the following expression
produces the absolute value of 'x':

     x >= 0 ? x : -x

   Each time the conditional expression is computed, only one of
IF-TRUE-EXP and IF-FALSE-EXP is used; the other is ignored.  This is
important when the expressions have side effects.  For example, this
conditional expression examines element 'i' of either array 'a' or array
'b', and increments 'i':

     x == y ? a[i++] : b[i++]

This is guaranteed to increment 'i' exactly once, because each time only
one of the two increment expressions is executed and the other is not.
*Note Arrays::, for more information about arrays.

   As a minor 'gawk' extension, a statement that uses '?:' can be
continued simply by putting a newline after either character.  However,
putting a newline in front of either character does not work without
using backslash continuation (*note Statements/Lines::).  If '--posix'
is specified (*note Options::), this extension is disabled.

© manpagez.com 2000-2025
Individual documents may contain additional copyright information.