Why does this if-statement combining assignment and an equality check return true?

后端 未结 4 689
醉梦人生
醉梦人生 2020-12-22 23:25

I\'ve been thinking of some beginner mistakes and I ended up with the one on the if statement. I expanded a bit the code to this:

int i = 0;
if          


        
4条回答
  •  青春惊慌失措
    2020-12-23 00:01

    Assuming your code actually looks like this:

    #include 
    using namespace std;
    
    int main()  {
        int i = 0;
        if (i = 1 && i == 0) {
            cout << i;
        }
    }
    

    Then this:

    if (i = 1 && i == 0) {
    

    evaluates as

     if (i = (1 && i == 0)) {
    

    and so i is set to 1.

提交回复
热议问题