So it seems like a lot of beginners tend to replace the comparison operator with the assignment operator. I understand the confusion, but what actually happens when you do this?
1 2 3 4 5 6
|
int c = 12;
int b = 7;
if(c == b)
//Do something....
|
//Ok now let's just replace the comparison with assignment
if(c = b)
//Do something... |
The first part is obvious, we don't need to talk about that. But the second part:
First off, it assigns the value stored at b, into c. And then it performs the condition. So, this can boil down to
if(12)
. A true is equal to one, and false is equal to zero (I believe, at least from C I think that's how it was). So unless you happen to assign a variable the value of 1, this type of situation will always be false? I seem to remember testing this before as I was helping a friend through a c++ class and he made this mistake, and the behavior was not as I expected. It actually went ahead and performed whatever it was, even though the value was not a 1. So what's the deal here? What exactly happens behind the scenes in these situations?
EDIT:
I guess I just found out that if you put a line of ----- in a code block here, it separates it all weird like. Interesting.