Variable changes on it's own in C++

前端 未结 2 789
礼貌的吻别
礼貌的吻别 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.

    0 讨论(0)
  • 2021-01-27 14:55

    As has been noted, in your if statements, you are using the assignment operator (=) but want the equality comparison operator (==). For your variable i the first if statement sets i equal to 0 and if(0) is the same as if(false). So your program goes to the first else-if which sets i equal to 1 and if(1) evaluates to true. Your code then finishes the block within else if (i = 1) {...} and then ends.

    0 讨论(0)
提交回复
热议问题