?留下一前pression空当三元条件运算符的行为: [英] ?: ternary conditional operator behaviour when leaving one expression empty
问题描述
我在写一个控制台应用程序,将尝试通过试错猜一个数字,它工作得很好,所有,但它留给我觉得这件事我心不在焉地写了某一部分,
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,
在code是:
#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);
我用((100 /(I&LT;&LT; = 1))?:1)
来确保,如果 100 /(I&LT ;&LT; = 1)
返回0(或假的)整个前pression将评估为1 ((100 /(I&LT;&LT; = 1))? :*** *** 1)
,和我离开的条件的一部分,如果它是真正的空((100 /(I&LT,将工作;&LT; = 1 ))_this space_:?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?
推荐答案
这是一个GNU C扩展(见的?:维基百科条目),因此便携性,你应该明确说明第二个操作数。
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:
a = x ?: y;
a = x ? x : y;
唯一的区别是在第一个声明中, X
总是被计算一次,而在第二个, X
将两次评估,如果这是真的。所以,唯一的区别是,当评估 X
有副作用。
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 evaluating x
has side effects.
无论哪种方式,我认为这是一个巧妙运用语法的......如果您有任何同情那些维护您的code,你应该明确说明操作数。 :)
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.
这篇关于?留下一前pression空当三元条件运算符的行为:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!