c语言三元运算符
Programmers use the ternary operator for decision making in place of longer if and else conditional statements.
程序员使用三元运算符代替较长的if和else条件语句进行决策。
The ternary operator take three arguments:
三元运算符采用三个参数:
- The first is a comparison argument 第一个是比较参数
- The second is the result upon a true comparison 第二是经过真正比较的结果
- The third is the result upon a false comparison 第三是错误比较的结果
It helps to think of the ternary operator as a shorthand way or writing an if-else statement. Here’s a simple decision-making example using if and else:
将三元运算符视为简写方式或编写if-else语句会有所帮助。 这是一个使用if和else的简单决策示例:
int a = 10, b = 20, c;
if (a < b) {
c = a;
}
else {
c = b;
}
printf("%d", c);
This example takes more than 10 lines, but that isn’t necessary. You can write the above program in just 3 lines of code using a ternary operator.
这个例子需要十行,但这不是必须的。 您可以使用三元运算符仅用3行代码编写以上程序。
句法 (Syntax)
condition ? value_if_true : value_if_false
condition ? value_if_true : value_if_false
The statement evaluates to value_if_true
if condition
is met, and value_if_false
otherwise.
如果满足condition
则该语句的值为value_if_true
,否则为value_if_false
。
Here’s the above example rewritten to use the ternary operator:
这是上面的示例重写为使用三元运算符:
int a = 10, b = 20, c;
c = (a < b) ? a : b;
printf("%d", c);
Output of the example above should be:
上面示例的输出应为:
10
c
is set equal to a
, because the condition a < b
was true.
c
设置为等于a
,因为条件a < b
为真。
Remember that the arguments value_if_true
and value_if_false
must be of the same type, and they must be simple expressions rather than full statements.
请记住,参数value_if_true
和value_if_false
必须具有相同的类型,并且它们必须是简单的表达式而不是完整的语句。
Ternary operators can be nested just like if-else statements. Consider the following code:
三元运算符可以像if-else语句一样嵌套。 考虑以下代码:
int a = 1, b = 2, ans;
if (a == 1) {
if (b == 2) {
ans = 3;
} else {
ans = 5;
}
} else {
ans = 0;
}
printf ("%d\n", ans);
Here's the code above rewritten using a nested ternary operator:
这是上面使用嵌套三元运算符重写的代码:
int a = 1, b = 2, ans;
ans = (a == 1 ? (b == 2 ? 3 : 5) : 0);
printf ("%d\n", ans);
The output of both sets of code above should be:
上面两组代码的输出应为:
3
c语言三元运算符