Encyclopedia  |   World Factbook  |   World Flags  |   Reference Tables  |   List of Lists     
   Academic Disciplines  |   Historical Timeline  |   Themed Timelines  |   Biographies  |   How-Tos     
Sponsor by The Tattoo Collection
?:
Main Page | See live article | Alphabetical index

?:

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

The operator is used as follows

condition ? value if true : value if false ;

The condition is evaluated as a Boolean expression. On the basis of the evaulation of the expression, the entire expression returns value if true if condition is true, and value if false otherwise.

The operator's usage is done so to minimize the amount of code used for a simple conditional assignment. 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
 if(day == WEEKEND)
     int opening_time = 12;
 else
     int opening_time = 9;

The two forms are equivalent. Note that neither value if true nor value if false expressions can be omitted.