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?
?:
) happens to be the only ternary operator in C (and in many similar languages), so it's commonly called "the ternary operator". The usage is perhaps a bit sloppy, but common. (The C standard never refers to?:
as a "ternary" operator. In fact it uses the phrase "ternary operator" only when discussing the semantics of thefma()
function, which computes(x × y) + z
.)