Node:The question mark operator, Next:The switch statement, Previous:Nested if statements, Up:Decisions
The ?
...:
... operator
The ?
...:
... operator is a sort of shorthand
if
...else
... statement. Because it is a little
cryptic, it is not often used, but the basic form is as follows:
(condition) ? expression1 : expression2;
The program evaluates condition. If it is true (not zero), then expression1 is returned; otherwise, expression2 is returned.
For example, in the short program below, the line
bas = (foo > bar) ? foo : bar;
assigns foo
to bas
if foo
is greater than bar
; otherwise, it assigns
bar
to bas
.
#include <stdio.h> int main() { int foo = 10; int bar = 50; int bas; bas = (foo > bar) ? foo : bar; printf("bas = %d\n\n", bas); return 0; }
The program will print bas = 50
as a result.