[英]How can I use the conditional operator to print an integer or a string value
In C how can I use a conditional operator inside of a printf statement utilizing two different data types? 在C语言中,如何在使用两种不同数据类型的printf语句中使用条件运算符? I would like to have the code below printing nothing instead of zero each time it encounters a even number. 我希望下面的代码每次遇到偶数时什么都不打印,而不是零。 I would also like to be able to print a string when it encounters certain numbers. 我还希望能够在遇到特定数字时打印字符串。
I tried type casting (char)list[i] but that results in an incompatiable type cast because the printf statement requires an integer. 我尝试了类型转换(char)list [i],但是由于printf语句需要一个整数,因此导致类型转换不兼容。
int fail = 0;
int list[] = {1, 2, 3, -1, 4};
int size = sizeof(list) / sizeof(list[0]);
for(int i = 0; i < size; i++) {
if(list[i] == -1) {
break;
}
printf("%d\n", (list[i] % 2 == 0) ? (i) : (fail));
}
The correct and readable approach is to use several calls to printf
, each with its own format and arguments: 正确且易读的方法是对printf
使用多个调用,每个调用都有自己的格式和参数:
if (list[i] % 2 == 0) {
printf("%d\n", i);
}
else if (i == 42) {
puts("The answer");
}
/* Otherwise, print nothing */
You could also do that with the ?:
operator: 您也可以使用?:
运算符:
(list[i] % 2 == 0) ? printf("%d\n", i) :
(i = 42) ? printf("%s\n", "The answer") :
0;
(This works because all three possible return values are the number of characters printed.) (之所以起作用,是因为所有三个可能的返回值都是打印的字符数。)
If you just want to print 0 as nothing instead of 0
, use 0 as the precision (not the width) of the format specifier: 如果只想将0打印为空而不是0
,请使用0作为格式说明符的精度 (而不是宽度):
printf("%.0d\n", i);
(In obfuscated code, you could force the value you wanted to hide to be 0 with a ternary operator. Or even with a multiply.) (在模糊代码中,您可以使用三元运算符将要隐藏的值强制为0。甚至使用乘法。)
C is a strongly-typed language, which means that the compiler needs to be able to deduce the type of any expression. C是一种强类型语言,这意味着编译器需要能够推断任何表达式的类型。 That includes ?:
expressions, so it is not possible for the second and third arguments of that operator to have incompatible types. 其中包括?:
表达式,因此该运算符的第二个和第三个参数不可能具有不兼容的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.