tags:

views:

230

answers:

4
   main()
   {
       int i=-3, j=2, k=0, m;
       m = ++i || ++j && ++k;
       printf("%d %d %d %d", i, j, k, m);
   }

Whats the output?

The output shows j==2 and k==0, implying that ++i was evaluated (and caused the || operator to short-circuit its right hand side) before the expression ++j && ++k which appears to contradict the fact that the && operator has higher precedence than ||.

Would someone explain why?

+2  A: 

-2 2 0 1

Lazy.

#include <stdio.h>

int main()
{

 int i=-3,j=2,k=0;
 int m=++i||++j&&++k;

 printf("%d %d %d %d",i,j,k,m);

}

Compile, run and see for youself.

gcc tmp.c -o tmp
karlphillip
My thoughts exactly
Tom
anurag
No. This is very nicely explained in Jerry Coffin's answer. The OP and others just have an understanding problem.
Carl Smotricz
+23  A: 

The output should be something like:

Error, line 2: 'm': undefined variable.

Edit: with that fixed, only the ++i should be evaluated. Precedence does not determine (or even affect) order of evaluation. Precedence means the expression is equivalent to ++i || (++j && ++k). Order of evaluation for || or && is always that the left operand is evaluated, then there's a sequence point. After the sequence point, the right operand is evaluated if and only if necessary to determine the final result (i.e., the right operand of || is evaluated if the left operand evaluated to zero; the right operand of && is evaluated if the left operand evaluated to non-zero).

In this expression, ++i is evaluated, then because it's the left operand of || and evaluated non-zero, none of the rest of the expression is evaluated.

Jerry Coffin
+1 for making me chuckle. I agree. :D
AJ
It was originally all one line, with the m being part of the declaration with the rest. When breaking it up, the editor apparently split the lines, inserting the error.
James Curran
@James - Even when it was a one liner there was a `;` between the k and the m.
Amardeep
+1  A: 

By way of explanation:

#include <stdio.h>

int main()
{
    if (-1)
        printf ("-1!\n");
    else
        printf ("Not -1.\n");
    return 0;
}

Negative numbers are not false in C. Always compare boolean values to 0 (or FALSE) or you can get bitten by if (worked == TRUE) giving false negatives.

Nathon
+1  A: 

The expression:

++i || ++j && ++k

Is equivalent to:

(++i) || ((++j) && (++k))

Explaining:

  1. ++i is evaluated -- (-2) || ((++j) && (++k));
  2. The || operator is evaluated -- (1);

Since 1 || anything evalutes true, the right operand is not evaluated. Thus, the && precedence doesn't matter here.

Now, try using a sub-expression, like this:

(++i || ++j) && ++k

Which is equivalent to:

((++i) || (++j)) && (++k)

Explaining:

  1. ++i is evaluated -- ((-2) || (++j)) && (++k);
  2. || is evaluated -- (1) && (++k)
  3. ++k is evaluated -- (1) && (1);
  4. Evaluates true;
jweyrich