Why does my condition run when the ball's position should be negative?

November 16, 2026 4 answers
Asked by _x19~mapcaddy.6

I'm testing a CLI ball animation in C++. The ball starts at y_pos 20, with velocity 5 and ground 200. An endless loop subtracts velocity from y_pos, then prints the position only if y_pos is greater than or equal to ground.

I expect that condition to stay false, but I eventually see a huge positive number. In the debugger, the position just decreases. What am I missing?

Answers

c.841~sparecrank

The loop keeps subtracting 5 without stopping. Eventually y_pos goes below the smallest value its signed int can represent, causing signed integer overflow.

On some builds, the value may appear to wrap to a large positive number, which would explain why the condition then passes. But signed overflow is undefined behavior in C++, so wrapping is not guaranteed. A debugger stepping through the first few iterations won't get anywhere near that point.

6f+mapgrommet_493:

That is integer overflow, not a buffer overflow. No buffer is involved in this example.

Reply to this answer
3r+canvaswhistle_672

Nothing prints at the starting position because the print is inside the condition, and the position is updated before the condition is checked. The first value checked is 15, not 20.

For this test, print y_pos before the loop and on each iteration outside the if block. Add a finite iteration limit so the test ends before overflow. Printing every iteration will also make the loop much slower, which explains why it can appear to behave differently.

Reply to this answer
4p!velvetcaddy_829

Decide which direction your coordinates move before choosing the ground check. With the current values, subtracting moves y_pos away from ground at 200, so that comparison won't become true through normal movement.

If falling is meant to increase y_pos toward 200, add the velocity and stop when the position reaches or passes the ground. If falling decreases y_pos, put the ground below the starting value and use a less than or equal comparison instead.

_x19~mapcaddy.6:

I was deliberately moving away from the ground to test the condition. The missing loop limit explains why that test didn't stay safe.

Reply to this answer
t.294~drainbutton

A signed integer overflow sanitizer can help catch the actual failure. With a compiler that supports it, enable undefined behavior sanitization and run the test. It can report the overflow at the subtraction rather than leaving you to infer it from a later print.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions