Issue
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.
Solution
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 int
s, 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.
Another difference is in the placement if your if(eCoada==false)
line.
In your working code, it’s after the for
loop finishes, which means that it only executes once.
In your broken code, it’s inside the for
loop, which means that every time the loop executes it prints a space. It also means that because you break
out of the loop immediately upon setting eCoada
to true
, you never execute the else
branch and never print an o
.
Answered By – Nathan Pierson
Answer Checked By – David Marino (BugsFixing Volunteer)