#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

Edited 5 Years Ago by Narue: Added code tags

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?

This article has been dead for over six months. Start a new discussion instead.