-1

I was going through a C objective book where a question comes:

#include<stdio.h>
#include<conio.h> 
int main()
{
    int i,j,k;
    i=j=k=1;
    k=++i||++j&&++k;
    printf("%d %d %d",i,j,k);
    return 0;
}

The output is:

2 1 1

In my view:

  1. k is incremented.

  2. j is incremented.

  3. i is incremented.

  4. k&&j will happen.

  5. i|| (k&&j)

So the output should be i=2,j=2,k=1. What am I missing?

Radiodef
  • 37,180
  • 14
  • 90
  • 125
mrigendra
  • 1,472
  • 3
  • 19
  • 33

1 Answers1

3

The expression k=++i||++j&&++k; causes undefined behaviour. You are trying to assign to k twice without an intervening sequence point.

Even if the assignment were to a different variable, your steps would be inaccurate - the logical operators have short-circuiting behaviour.

Edit: OP says he changed the expression to a=++i||++j&&++k. I'm going to rewrite it fully parenthesized and with some spaces:

a = ++i || (++j && ++k);

In this case, only the ++i is evaluated, due to short-circuiting behaviour of the || operator.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469