Why does my condition trigger when the value should be negative?

0
6
Asked By MellowCedar42 On

I'm writing a small command-line simulation of a falling ball in C++. For testing, I intentionally set the ball's position and velocity so that y_pos decreases on every loop iteration. However, the condition `if (ball.y_pos >= ball.ground)` eventually runs and prints a huge value such as `Falling 2144211756`, even though y_pos should be getting smaller. In the debugger, the values initially decrease as expected. Why does the condition eventually become true?

3 Answers

Answered By QuietOrbit7 On

The loop is infinite, so y_pos keeps decreasing forever. Eventually it goes below the minimum value representable by a signed int. In C++, signed integer overflow is undefined behavior, but on many systems it appears to wrap around from a very negative number to a very large positive number. Once that happens, `ball.y_pos >= ball.ground` becomes true and you see the large output. Add a stopping condition to the loop and print y_pos on every iteration if you want to observe the transition.

BrightHarbor19 -

The usual term is integer overflow; there isn't a buffer involved here. Also, the exact wraparound behavior should not be relied on for signed integers because the C++ standard treats it as undefined behavior.

Answered By SilverMaple63 On

Your comparison itself is behaving correctly. Starting at 20 and subtracting 5 means the value will never become greater than or equal to 200 during normal execution. The problem is that `while (true)` never stops, so the program continues modifying the value long after it has passed the position you care about. Use a meaningful loop condition or stop when the ball reaches the ground, for example by checking whether y_pos is still within the simulation range.

Answered By CobaltPine28 On

Printing y_pos inside the loop makes the behavior easier to see because you'll observe it decreasing for a long time before the integer reaches its limit. A debugger may appear to show normal behavior simply because you're only inspecting the early iterations or pausing before the overflow occurs. If you want to test a reversed direction, make sure the termination condition is reversed as well, rather than leaving the loop unconditional.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.