Variable changes on it's own in C++

前端 未结 2 790
礼貌的吻别
礼貌的吻别 2021-01-27 14:21

I have a loop going through an array trying to find which index is a string. It should solve for what that value should be. I can\'t figure out why, but as soon as the if statem

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-27 14:47

    That's because operator= is the assignment operator in C++ (and most languages, actually). That changes the value of the variable to the value on the other side. So, for instance:

    x = 0
    

    will change the value of x to 0. Doesn't matter if it's in an if statement. It will always change the value to 0 (or whatever the right hand side value is).

    What you are looking for is operator==, which is the comparison (aka relational) operator in C++/ That asks the question "Are these two things equal?" So, for instance:

    x == 0
    

    asks is x is equal to 0.

提交回复
热议问题