BIGpedia.com - ?: - Encyclopedia and Dictionary Online
encyclopedia search

?:

?: is a noted example of a ternary operator, which is part of the syntax for a basic conditional expression in C, C++, Perl, Ruby, PHP, JavaScript and Java. It is often used in conditional assignment statements.

This ternary operator is used in an expression 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.

This ternary operator's usage is to minimize the amount of code used for a simple conditional assignment statement. (In this case, the expression is converted into a statement by appending a semicolon ; to the expression.) For example, if we wish to implement some C code to change a shop's opening hours to 12 o'clock in weekends, and 9 o'clock on weekdays, we may use

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

instead of the more verbose

 int opening_time;
 if(day == WEEKEND)
     opening_time = 12;
 else
     opening_time = 9;

The two forms are equivalent. Note that neither value if true nor value if false expressions can be omitted from the ternary operator without an error report upon parsing.



The contents of this article are licensed from Wikipedia.org under the GNU Free Documentation License.
How to see transparent copy

01-04-2007 01:21:04