easy ones for somebody

I'm looking for help on 2 seemingly easy codes.
Does anyone know why this code returns 10? Shouldn't it return 50? the if statement says if a = b, which is does not, so else a * b should be the output.
int a = 5, b = 10;
if (a = b)
cout << a << endl;
else
cout << a * b << endl;

and this one: Why does it return 5? If the while is set to (a < 0) and a is initialized to 5, a is never less than 0....
int a = 5;
do{
cout << a << endl;;
a +=2;
} while (a < 0);


(a = b)
This sets the value of a to the same as b, and because the value in question is not zero, the statement is not zero, which is the same as true, so the if statement passes and you get cout << a << endl;. I suspect you meant
(a == b)

The second one; in a do-while loop, the condition is checked AFTER each time the loop is run through. So the loop runs once, THEN the condition is checked and found to be false, so the loop ends.
Last edited on
A do / while statement is different from a while statement in that it will run the code at least once before it will check the while. So your code initializes a as 5, then outputs the a as 5, then adds 2 to a making it seven. finally it checks to see if a is less then 0, it isn't so it won't repeat.

In your first function, you are not checking to see if a is equal to b, you would do a == b if you were checking, instead you are setting b equal to a, so then a is outputted because if checks to see if something is 0 which is known as false, since a is not 0, it is automatically true.

I make the mistake of missing an = all the time, so don't feel bad. just change your a = b to a == b and it will work the way you like.
I make the mistake of missing an = all the time


I got into the habit of yoda-coding to stop that a lot of the time.

Instead of
if (x == 7)
I use
if (7 == x)

If I mistype and enter
if (7 = x)
it won't compile.

Won't work with two left-side objects, but with a right-side object such as 7 it will.
I like that method, I never purposely doing that.
Topic archived. No new replies allowed.