#include<stdio.h>
#include<iostream.h>
int main()
{
    int x,y,z;
    x=y=z=5;
    z=++x||++y&&++z;
    printf("x=%d,y=%d,z=%d",x,y,z);
}

why the output is x=6,y=5,z=1??
shouldn't it be x=6,y=6,z=1

Why do you think y should be 6?

because we are pre-incrementing y

And why do you think that the pre-increment of y is ever executed?

because we are pre-incrementing y

No, you're not. The || operator is short circuited, which means the ++x part evaluates to true and terminates the expression. z is assigned a true value (1), and y doesn't get updated because that half of the expression wasn't evaluated. Consider if ++x evaluates to false:

#include<cstdio>
using namespace std;

int main()
{
    int x,y,z;
    x=-1;
    y=z=5;
    z=++x||++y&&++z;
    printf("x=%d,y=%d,z=%d",x,y,z);
}

Aw, gee ... here I was trying to lead the OP gently to the right answer and two people jumped in and spoiled it :-)

That said, I would like to make one slightly subtle point. Suppose we eliminate the short-circuit evaluation:

z = ++x | ++y & ++z;

Now the effect of the statement is undefined because it modifies z twice between sequence points.

Now the effect of the statement is undefined because it modifies z twice between sequence points.

I missed that even after originally thinking this question would boil down to that rule. The moral of the story is that undefined behavior can catch anybody who's not being careful. ;)

I missed that even after originally thinking this question would boil down to that rule. The moral of the story is that undefined behavior can catch anybody who's not being careful. ;)

Yeah--bugs are like that, aren't they?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.