Ternary conditional operator - Biblioteka.sk

Upozornenie: Prezeranie týchto stránok je určené len pre návštevníkov nad 18 rokov!
Zásady ochrany osobných údajov.
Používaním tohto webu súhlasíte s uchovávaním cookies, ktoré slúžia na poskytovanie služieb, nastavenie reklám a analýzu návštevnosti. OK, súhlasím


Panta Rhei Doprava Zadarmo
...
...


A | B | C | D | E | F | G | H | CH | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

Ternary conditional operator
 ...

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 (abbreviated iif). 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 the most common, but alternative syntax 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).

It originally comes from CPL, in which equivalent syntax for e1 ? e2 : e3 was e1e2, e3.[1][2]

Although many ternary operators are possible, the conditional operator is so common, and other ternary operators so rare, that the conditional operator is commonly referred to as the ternary operator.

Variations

The detailed semantics of "the" ternary operator as well as its syntax differs significantly from language to language.

A top level distinction from one language to another is whether the expressions permit side effects (as in most procedural languages) and whether the language provides short-circuit evaluation semantics, whereby only the selected expression is evaluated (most standard operators in most languages evaluate all arguments).

If the language supports expressions with side effects but does not specify short-circuit evaluation, then a further distinction exists about which expression evaluates first—if the language guarantees any specific order (bear in mind that the conditional also counts as an expression).

Furthermore, if no order is guaranteed, a distinction exists about whether the result is then classified as indeterminate (the value obtained from some order) or undefined (any value at all at the whim of the compiler in the face of side effects, or even a crash).

If the language does not permit side-effects in expressions (common in functional languages), then the order of evaluation has no value semantics—though it may yet bear on whether an infinite recursion terminates, or have other performance implications (in a functional language with match expressions, short-circuit evaluation is inherent, and natural uses for the ternary operator arise less often, so this point is of limited concern).

For these reasons, in some languages the statement form variable = condition ? expr1 : expr2; can have subtly different semantics than the block conditional form if (condition) { variable = expr1; } else { variable = expr2;} (in the C language—the syntax of the example given—these are in fact equivalent).

The associativity of nested ternary operators can also differ from language to language. In almost all languages, the ternary operator is right associative so that a == 1 ? "one" : a == 2 ? "two" : "many" evaluates intuitively as a == 1 ? "one" : (a == 2 ? "two" : "many"), but PHP in particular is notoriously left-associative,[3] and evaluates as follows: (a == 1 ? "one" : a == 2) ? "two" : "many", which is rarely what any programmer expects. (The given examples assume that the ternary operator has low operator precedence, which is true in all C-family languages, and many others.)

Equivalence to map

The ternary operator can also be viewed as a binary map operation.

In R—and other languages with literal expression tuples—one can simulate the ternary operator with something like the R expression c(expr1,expr2) (this idiom is slightly more natural in languages with 0-origin subscripts). Nested ternaries can be simulated as c(expr1,expr2,expr3) where the function which.first returns the index of the first true value in the condition vector. Note that both of these map equivalents are binary operators, revealing that the ternary operator is ternary in syntax, rather than semantics. These constructions can be regarded as a weak form of currying based on data concatenation rather than function composition.

If the language provides a mechanism of futures or promises, then short-circuit evaluation can sometimes also be simulated in the context of a binary map operation.

Conditional assignment

?: is used as follows:

condition ? value_if_true : value_if_false

The condition is evaluated true or false as a Boolean expression. On the basis of the evaluation of the Boolean condition, the entire expression returns value_if_true if condition is true, but value_if_false otherwise. Usually the two sub-expressions value_if_true and value_if_false must have the same type, which determines the type of the whole expression. The importance of this type-checking lies in the operator's most common use—in conditional assignment statements. In this usage it appears as an expression on the right side of an assignment statement, as follows:

variable = condition ? value_if_true : value_if_false

The ?: operator is similar to the way conditional expressions (if-then-else constructs) work in functional programming languages, like Scheme, ML, Haskell, and XQuery, since if-then-else forms an expression instead of a statement in those languages.

Usage

The conditional operator's most common usage is to make a terse simple conditional assignment statement. For example, if we wish to implement some C code to change a shop's normal opening hours from 9 o'clock to 12 o'clock on Sundays, we may use

int opening_time = (day == SUNDAY) ? 12 : 9;

instead of the more verbose

int opening_time;

if (day == SUNDAY)
    opening_time = 12;
else
    opening_time = 9;

The two forms are nearly equivalent. Keep in mind that the ?: is an expression and if-then-else is a statement. Note that neither the true nor false portions can be omitted from the conditional operator without an error report upon parsing. This contrasts with if-then-else statements, where the else clause can be omitted.

Most of the languages emphasizing functional programming don't need such an operator as their regular conditional expression(s) is an expression in the first place e.g. the Scheme expression (if (> a b) a b) is equivalent in semantics to the C expression (a > b) ? a : b. This is also the case in many imperative languages, starting with ALGOL where it is possible to write result := if a > b then a else b, or Smalltalk (result := (a > b) ifTrue: ifFalse: ) or Ruby (result = if a > b then a else b end, although result = a > b ? a : b works as well).

Note that some languages may evaluate both the true- and false-expressions, even though only one or the other will be assigned to the variable. This means that if the true- or false-expression contain a function call, that function may be called and executed (causing any related side-effects due to the function's execution), regardless of whether or not its result will be used. Programmers should consult their programming language specifications or test the ternary operator to determine whether or not the language will evaluate both expressions in this way. If it does, and this is not the desired behaviour, then an if-then-else statement should be used.

ActionScript 3

condition ? value_if_true : value_if_false

Ada

The 2012 edition of Ada has introduced conditional expressions (using if and case), as part of an enlarged set of expressions including quantified expressions and expression functions. The Rationale for Ada 2012[4] states motives for Ada not having had them before, as well as motives for now adding them, such as to support "contracts" (also new).

Pay_per_Hour := (if Day = Sunday
   then 12.50
   else 10.00);

When the value of an if_expression is itself of Boolean type, then the else part may be omitted, the value being True. Multiple conditions may chained using elsif.

ALGOL 68

Both ALGOL 68's choice clauses (if and the case clauses) provide the coder with a choice of either the "bold" syntax or the "brief" form.

  • Single if choice clause:
if condition then statements  fi
"brief" form:  ( condition | statements | statements )
  • Chained if choice clause:
if condition1 then statements elif condition2 then statements  fi
"brief" form:  ( condition1 | statements |: condition2 | statements | statements )

APL

With the following syntax, both expressions are evaluated (with value_if_false evaluated first, then condition, then value_if_false):

result  value_if_true  condition  value_if_false

This alternative syntax provides short-circuit evaluation:

result  { condition : expression_if_true  expression_if_false } 

AWK

result = condition ? value_if_true : value_if_false

Bash

A true ternary operator only exists for arithmetic expressions:

((result = condition ? value_if_true : value_if_false))

For strings there only exist workarounds, like e.g.:

result=$( "$a" = "$b"  && echo "value_if_true" || echo "value_if_false")

Where "$a" = "$b" can be any condition construct can evaluate. Instead of the there can be any other bash command. When it exits with success, the first echo command is executed, otherwise the second one is executed.

Cedit

A traditional if-else construct in C is written:

if (a > b) {
    result = x;
}
else {
    result = y;
}

This can be rewritten as the following statement:

result = a > b ? x : y;

As in the if-else construct only one of the expressions 'x' and 'y' is evaluated. This is significant if the evaluation of 'x' or 'y' has side effects.[5] The behaviour is undefined if an attempt is made to use the result of the conditional operator as an lvalue.[5]

A GNU extension to C allows omitting the second operand, and using implicitly the first operand as the second also:

a == x ? : y;

The expression is equivalent to

a == x ? (a == x) : y;

except that expressions a and x are evaluated only once. The difference is significant if evaluating the expression has side effects. This shorthand form is sometimes known as the Elvis operator in other languages.

C#edit

In C#, if condition is true, first expression is evaluated and becomes the result; if false, the second expression is evaluated and becomes the result. As with Java only one of two expressions is ever evaluated.

// condition ? first_expression : second_expression;

static double sinc(double x) 
{
     return x != 0.0 ? Math.Sin(x) / x : 1.0;
}

C++edit

Unlike in C, the precedence of the ?: operator in C++ is the same as that of the assignment operator (= or OP=), and it can return an lvalue.[6] This means that expressions like q ? a : b = c and (q ? a : b) = c are both legal and are parsed differently, the former being equivalent to q ? a : (b = c).

In C++ there are conditional assignment situations where use of the if-else statement is impossible, since this language explicitly distinguishes between initialization and assignment. In such case it is always possible to use a function call, but this can be cumbersome and inelegant. For example, to pass conditionally different values as an argument for a constructor of a field or a base class, it is impossible to use a plain if-else statement; in this case we can use a conditional assignment expression, or a function call. Bear in mind also that some types allow initialization, but do not allow assignment, or even that the assignment operator and the constructor do totally different things. This last is true for reference types, for example:

#include <iostream>
#include <fstream>
#include <string>

int main(int argc, char *argv)
{
    std::string name;
    std::ofstream fout;

    if (argc > 1 && argv1)
    {
        name = argv1;
        fout.open(name.c_str(), std::ios::out | std::ios::app);
    }

    std::ostream &sout = name.empty() ? std::cout : fout;

    sout << "Hello, world!\n";

    return 0;
}
Zdroj:https://en.wikipedia.org?pojem=Ternary_conditional_operator
Text je dostupný za podmienok Creative Commons Attribution/Share-Alike License 3.0 Unported; prípadne za ďalších podmienok. Podrobnejšie informácie nájdete na stránke Podmienky použitia.






Text je dostupný za podmienok Creative Commons Attribution/Share-Alike License 3.0 Unported; prípadne za ďalších podmienok.
Podrobnejšie informácie nájdete na stránke Podmienky použitia.

Your browser doesn’t support the object tag.

www.astronomia.sk | www.biologia.sk | www.botanika.sk | www.dejiny.sk | www.economy.sk | www.elektrotechnika.sk | www.estetika.sk | www.farmakologia.sk | www.filozofia.sk | Fyzika | www.futurologia.sk | www.genetika.sk | www.chemia.sk | www.lingvistika.sk | www.politologia.sk | www.psychologia.sk | www.sexuologia.sk | www.sociologia.sk | www.veda.sk I www.zoologia.sk