Home > OS >  Same code, one works one doesn't. What's different?
Same code, one works one doesn't. What's different?

Time:03-05

i'm an beginner programmer, this is my first time posting. I'm currently writing a snake game in c . Most of the game wasn't so hard to implement but when it came to the tail of the snake the entire program broke. I spent like 2 hours trying to figure out what was wrong and then i decided to try to rewrite the problematic code. From my understanding i haven't changed a thing but now it works. Can someone explain to me what changed? Here is the code, the commented one is not working the other works fine:

   else { 
            bool eCoada = false;
            for (int s = 0; s <= ntail; s  )
            {
                if (tail[s].height == j && tail[s].width == k)
                { eCoada = true; break; }

            }
            if (eCoada == false)  cout << " ";
            else cout << "o";
        }
    /*  else  {
            bool eCoada = false;
        for (int s = 0;s <= ntail; s  )
        {
            if (tail[s].height==j &&  k==tail[s].width==k)
            { eCoada = true; break; }
            if (eCoada==false)  cout << " ";
            else cout << "o";
        }
               
            }*/

Also i should mention that this code is a part of a function, if you want me to post the full code i will do so.

CodePudding user response:

k==tail[s].width==k is not the same as tail[s].width == k. You may think you've written something like (k == tail[s].width) && (tails[s].width == k. But C doesn't automatically put in && operators like that. What actually happens is that the associativity of the == operator is left to right. So what that actually means is

(k == tails[s].width) == k

Assuming k and tails[s].width are ints, that means (k == tails[s].width) is a bool. The comparison between that and k will be checking if k is 0 or 1, instead of checking if it matches the width as intended.

CodePudding user response:

C , nor any other language that I know of, doesn't allow multiple comparisons in one statement. You can't say is x == y == z, you must break them up. if(x ==y && y == z)

  • Related