?:将一个表达式留空时的三元条件运算符行为
我正在编写一个控制台应用程序,它会尝试通过反复试验来“猜测”一个数字,它工作得很好,但它让我对我心不在焉地写的某个部分感到疑惑,
代码是:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,i,a,cc;
for(;;){
scanf("%d",&x);
a=50;
i=100/a;
for(cc=0;;cc++)
{
if(x<a)
{
printf("%d was too big\n",a);
a=a-((100/(i<<=1))?:1);
}
else if (x>a)
{
printf("%d was too small\n",a);
a=a+((100/(i<<=1))?:1);
}
else
{
printf("%d was the right number\n-----------------%d---------------------\n",a,cc);
break;
}
}
}
return 0;
}
更具体地说,是让我困惑的部分 我是否
a=a+((100/(i<<=1))?:1);
//Code, code
a=a-((100/(i<<=1))?:1);
使用 ((100/(i<<=1))?:1)
来确保 100/(i<<=1)
返回0(或 false)整个表达式将计算为 1 ((100/(i<<=1))?:***1***)
,并且我留下了如果它是 true 空 ((100/(i<<=1))? _this space_ :1)
,它似乎可以正常工作,但是离开该部分是否有任何风险条件为空?
I was writing a console application that would try to "guess" a number by trial and error, it worked fine and all but it left me wondering about a certain part that I wrote absentmindedly,
The code is:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,i,a,cc;
for(;;){
scanf("%d",&x);
a=50;
i=100/a;
for(cc=0;;cc++)
{
if(x<a)
{
printf("%d was too big\n",a);
a=a-((100/(i<<=1))?:1);
}
else if (x>a)
{
printf("%d was too small\n",a);
a=a+((100/(i<<=1))?:1);
}
else
{
printf("%d was the right number\n-----------------%d---------------------\n",a,cc);
break;
}
}
}
return 0;
}
More specifically the part that confused me is
a=a+((100/(i<<=1))?:1);
//Code, code
a=a-((100/(i<<=1))?:1);
I used ((100/(i<<=1))?:1)
to make sure that if 100/(i<<=1)
returned 0 (or false) the whole expression would evaluate to 1 ((100/(i<<=1))?:***1***)
, and I left the part of the conditional that would work if it was true empty ((100/(i<<=1))? _this space_ :1)
, it seems to work correctly but is there any risk in leaving that part of the conditional empty?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个 GNU C 扩展(参见 ?: wikipedia 条目),因此为了可移植性您应该明确声明第二个操作数。
在“true”的情况下,它返回条件的结果。
以下语句几乎是等效的:
唯一的区别是在第一个语句中,
x
始终计算一次,而在第二个语句中,如果为 true,x
将计算两次。所以唯一的区别是评估 x 时会产生副作用。不管怎样,我认为这是语法的微妙使用......如果您对维护代码的人有任何同情心,您应该明确说明操作数。 :)
另一方面,对于常见用例来说,这是一个很好的小技巧。
This is a GNU C extension (see ?: wikipedia entry), so for portability you should explicitly state the second operand.
In the 'true' case, it is returning the result of the conditional.
The following statements are almost equivalent:
The only difference is in the first statement,
x
is always evaluated once, whereas in the second,x
will be evaluated twice if it is true. So the only difference is when evaluatingx
has side effects.Either way, I'd consider this a subtle use of the syntax... and if you have any empathy for those maintaining your code, you should explicitly state the operand. :)
On the other hand, it's a nice little trick for a common use case.
这是 C 语言的 GCC 扩展 。当
?:
之间没有出现任何内容时,则在真实情况下使用比较的值。This is a GCC extension to the C language. When nothing appears between
?:
, then the value of the comparison is used in the true case.