0
int xx = 0;
if(xx = 0 || xx == 0) printf("4"); // if(TRUE||TRUE) then printf("4")
if(xx == 0) printf("5"); //xx been changed to 1??
printf("6\n"); 

I thought the output will be 456, but the output is 46. Why?

Chris Chou
  • 832
  • 1
  • 6
  • 9
  • @Steve where did you find `x`? – Sourav Ghosh May 23 '19 at 08:38
  • @WeatherVane Yeah, I was also thinking the same, but that was only tagged c++, is not it? Some will start complaining about it. I'll add it anyways, let's see. – Sourav Ghosh May 23 '19 at 08:40
  • Looks like a duplicate of [this question](https://stackoverflow.com/questions/56264674/why-does-this-if-statement-return-true) ? – m.raynal May 23 '19 at 08:41
  • 1
    This question is most certainly **not** a duplicate of the suggested question. It presents a similar, yet **different** scenario. Some users here are too hasty and reckless on the question-closing trigger, and that's a shame IMO. – goodvibration May 23 '19 at 08:43
  • 2
    @goodvibration it is not **identical**, but the root cause is the same: the assignment isn't quite as straightforward as it seems. – Weather Vane May 23 '19 at 08:47
  • 1
    @goodvibration seems like an attempt at karma farming from someone who saw that the other question somehow got 20 upvotes. Apparently getting started with SO rep is a problem so people turn to that sort of technique – M.M May 23 '19 at 08:52
  • @M.M good point: someone else spotted the question which was in the side panel a liitle earlier. – Weather Vane May 23 '19 at 08:55

1 Answers1

5

According to operator precedence, operator|| has higher precedence than operator=, then

if(xx = 0 || xx == 0) 

is same as

if(xx = (0 || xx == 0))

i.e. xx is assigned by 0 || xx == 0; which is true, then implicitly converted to 1 and assigned to xx (because xx is an int), then xx is evaluated for the if condition and it implicitly converts to bool with value true; that's why you got the output "4". And since xx has been assigned to 1, you didn't get the output "5".

I think what you want should be

if(xx == 0 || xx == 0)
//    ^^
songyuanyao
  • 169,198
  • 16
  • 310
  • 405