Reputation: 7161
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.
Upvotes: 2
Views: 1328
Reputation: 409136
Lets break this down into its separate operations:
i++ && j++
: This will be the same as -1 && 0
, which is false (i.e. 0).i
and j
are then increased to 0
and 1
respectively.0 && k++
: The zero is from the previous logical operation, the result is false since the first operator is false.k
is not increased, because of the shortcut nature of the logical operators.0 || l
: The zero is still from the previous logic operation, it is 0 || 2
and the result will be true, i.e. 1
.l
is increased to 3
.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.
Upvotes: 4
Reputation: 13025
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. :)
Upvotes: 7
Reputation: 6606
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.
Upvotes: 1