Help with understanding

There's this line of code that I don't understand:
1
2
3
4
5
6
  int a=0, b=2, c=4;
if (a = c-b)
cout<< b << endl;
else
cout<< c << endl;
cout << (a == b-c);


First, a isn't equal to c-b, so why would it cout b? and also I thought the last line would cout a 2, but that's not the case. can someone please explain why?
if (a = c-b)

this assigns the value of c-b to a. is this supposed to compare equality (==)?


edit:
this will print the result of comparison, 0 = false, 1 = true
cout << (a == b-c);
Last edited on
So just want to be clear:

the first a = c-b assigns the value 2 to a

and because the value has been assigned, the printed result of a == c-b becomes true?

second question, kinda unrelated

what does *(arr+i) mean?
Last edited on
Is that if condition correct? You usually don't want to assign values in an if condition, you want to compare values. Is it meant to compare the value of a (0) to c-b (2)?

a == c-b isn't the comparison being done there, it's a == b-c.
No, the IF statement isn't comparing the value, it's actually assigning a to c-b. It's my first time seeing it, so wasn't sure how to approach it.
First, a isn't equal to c-b, so why would it cout b?


You seemed to be expecting it to be making a comparison and that's what would usually happen in an if condition. It's a common typo to use = when == should be used, that's why I asked if the code was intended to assign or compare.

Last edited on
Topic archived. No new replies allowed.