Question

Can some one explain why the output of program is

0 1 1 3 1

void main(void)
{
      int i=-1,j=0,k=1,l=2,m;

      m=i++&&j++&&k++||l++;

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

}

Main concern is "why k is not incremented".

FYI..I am compiling the program in VC++ editor Windows 7 32 bit. Many Thanks in advance.

Was it helpful?

Solution

Roughly:

To evaluate i++&&j++, compiler evaluated i first. The result is -1. -1 is stored in a temporary variable. Then i got incremented.

Because -1 is not zero, compiler evaluated j, which is 0. Compiler now evaluated -1 && 0, which is 0. Then j got incremented.

At this point, i = 0 and j = 1. Remaining expression: m=0&&k++||l++;

To evaluate 0&&k++, compiler noted that the first operand is 0. The result must be 0 so compiler didn't evaluate k or k++. Remaining expression: m=0||l++;

I hope you can do the rest. :)

OTHER TIPS

Lets break this down into its separate operations:

  1. i++ && j++: This will be the same as -1 && 0, which is false (i.e. 0).
  2. i and j are then increased to 0 and 1 respectively.
  3. 0 && k++: The zero is from the previous logical operation, the result is false since the first operator is false.
  4. k is not increased, because of the shortcut nature of the logical operators.
  5. 0 || l: The zero is still from the previous logic operation, it is 0 || 2 and the result will be true, i.e. 1.
  6. l is increased to 3.
  7. The result of the logical operations is assigned to m, which now becomes true (i.e. 1)

The whole expression causes i, j and l to be increased, and m to become 1. Just the result you are seeing.

your value is getting calculated like below

m=((((i++)&&j++)&&k++)||l++); 

since all ++ are post increment so during calculation of m all variable have same value what you have initialised but on the next line during print they all are incremented.Last is || so final TRUE will return to value of m.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top