C ternary operator

166 views Asked by At

While studying C I faced something that is completely confusing my mind.

The expression is:

exp(V*log(i))?i%2?s:s--:s++;

If ternary operator is Question?Positive:Negative; I thought it was something like:

if(pow(i,V)==1&&(i%2)==0)
    s--;
 else
    s++;

However, the s does not enter in the question, should I ask what does the first expression mean?

The program worked perfectly, but I could not understand why.

The original program is:

main(){
    #define V 1

    int a, s=0, i;
    for(i=1000;i>=0;i--)
        exp(V*log(i))?i%2?s:s--:s++;
    exp(V*log(i))?printf("%d\t%d\t",-s,i):printf("%d\t%d\t", s,-i);
    getch();
}
2

There are 2 answers

2
Filip Bulovic On BEST ANSWER

If exp(Vlog(i)) is true then test is it odd i%2==1 if it is return s if even return s-- if exp(Vlog(i)) is false return s++ If you write it like this than is easier to see:

exp(V*log(i))?(i%2?s:s--):s++;
0
meneldal On

The ternary operator tests if an expression is true. To understand this case you need to analyse it and separate the two uses of the operator:

exp(V*log(i))?i%2?s:s--:s++;

This translates to

if(exp(V*log(i))
    if(i%2)
       s;
    else
       s--;
else
    s++;

The only difference is that it is an expression and a single statement instead of the if/else version. It always returns the current value of s but changes it depending on the condition.

If exp refers to the exponential function, then unless the output is -inf the output will be !=0 so the value will evaluate to true. Note that nan will also evaluate to false and nan is the output for log when the value is outside its domain.

So basically you could translate this with a much simpler expression (unless V is zero, the value for i==0 would change):

i>0?s++:i%2?s:s--;