-3

For example in the code below

int x,y,z;
x=y=z=1;
z = ++x && ++y || ++z;
cout<<x<<y<<z;

The output is 2 2 1. I guess it is because compiler knew that '++x && ++y' gives a 'true', so it skipped the remaining line || ++z.

However, if I replace it with the code below:

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

the output is still 2 2 1. shouldn't it be 2 2 2, because all parts of ANDs '++x' , '++y' , '++z' has to be evaluated.

Dave S
  • 20,507
  • 3
  • 48
  • 68

1 Answers1

1

I guess it is because compiler knew that '++x && ++y' gives a 'true', so it skipped the remaining line '|| ++z'.

That's correct. It's not necessarily done at compile time though, it could be performed at run time in a more complex situation (as the compiler can't guarantee to know the values within each variable.

That's not why z == 1 though.

You're setting z = ++x && ++y && ++z, which implicitly casts the boolean produced by the && to an integer. The integer representation of the boolean true is 1, therefore z == 1.

n00dle
  • 5,949
  • 2
  • 35
  • 48
  • 1
    It could be done at compile-time; it's an easy optimization given that x, y and z are set just before the statement. And afaik, it is still UB, so the value of z at the end is unspecified. – rici May 17 '14 at 21:35
  • Fair enough that is true for this toy example, I was thinking in the general case. I'll add "necessarily" :) It is UB, but in this case, is my suggestion not the logical answer? – n00dle May 17 '14 at 21:37
  • It's certainly the boolean answer :) It's probably the explanation, but it still cannot be relied upon to always work. (Not my downvote, by the way.) – rici May 17 '14 at 21:39