The conditional operator is a special operator in the C language similar to an if statement, which consists of a symbol? And: The format is expression 1? Expression 2: Expression 3, expression 1, expression 2, and expression 3 can be any type of expression. An expression consisting of a conditional operator is called a conditional expression. The conditional operator is the only ternary operator in the C operator that requires 3 operands.
A conditional expression is calculated by first calculating the value of expression 1, if the value is not 0 (that is, the result is true). Evaluates the value of expression 2 and takes its value as the value of the entire conditional expression, otherwise (the result is 0, false) evaluates the value of expression 3 and takes its value as the value of the entire conditional expression.
The conditional operators have precedence over the assignment operator, but are below the arithmetic operator, logical, and relational operator.
The conditional operator makes the program shorter, but sometimes makes it difficult to read and is used with caution.
/************************************** * CONDITIONAL_OPERATOR.C * * * *
The conditional operator in the C language *
**************************************/
#include <stdio.h>
int Max (int i, int j)
{
return i > J? i:j;
}
int main ()
{
int i = 1;
int j = 2;
int k = 0;
printf ("I =%d, j =%d, K =%d\n", I, J, K);
K = i > J? I:j;
printf ("I > J?" The value of I:j is:%d\n ", k);
K = (i >= 0 i:0) + j;
printf ("(I >= 0?") i:0) + J has the value of:%d\n ", k);
k = i >= 0? I:0 + j;
printf ("I >= 0"?) The value of I:0 + j is:%d\n ", k);
printf (maximum value in "I and j =%d\n", i > J i:j);
printf ("Max in I and j =%d\n", Max (i,j));
return 0;
}
Reference Documents K.N King, Lu Xiufeng. C Language Programming-modern methods. People's postal Press