条件运算符 (conditional operator) 是唯一一个三元运算符.
格式: 表达式 1 ? 表达式 2 : 表达式 3
以上构成一个条件表达式 (conditional expression).
当表达式 1 为真时, 条件运算表达式的值为表达式 2 的值, 否则条件运算表达式的值为表达式 3 的值.
表达式1为真,则只算表达式2,表达式3不计算。表达式1为假,则只算表达式3,表达式2不算。
条件运算符的结合方向是自右至左.
条件表达式可以嵌套, 即其中的表达式又是一个条件表达式.
int a, b, c, d;
a > b ? a : c > d ? c : d;
相当于:
a > b ? a : (c > d ? c : d);
条件运算符可以替代 if else, 代码更加简洁, 编译器生成的机器码也更简洁.
程序示例:
#include<stdio.h>
#define COVERAGE 200 // 每一罐油漆可以粉刷的面积
int main(void)
{
int sq; // 需要粉刷的面积
int cans; // 需要的罐数
printf("Enter the square to be painted (Enter q to quit): ");
while (scanf("%d", &sq) == 1)
{
cans = sq / COVERAGE;
cans = sq % COVERAGE == 0 ? cans : cans + 1;
printf("You need %d %s.\n", cans, cans == 1 ? "can" : "cans");
printf("Enter the square to be painted (Enter q to quit): ");
}
return 0;
}
结果:
Enter the square to be painted (Enter q to quit): 199
You need 1 can.
Enter the square to be painted (Enter q to quit): 200
You need 1 can.
Enter the square to be painted (Enter q to quit): 201
You need 2 cans.
Enter the square to be painted (Enter q to quit): q