Why does my conditional run even when the value should be below the limit?

0
0
Asked By MellowPine47 On

I'm testing a simple falling-ball simulation in C++. The ball starts at y_pos = 20, its velocity is 5, and ground is set to 200. Each loop subtracts the velocity from y_pos, then checks whether y_pos is greater than or equal to ground. Since the loop is currently while(true), I expected the condition never to run because y_pos keeps decreasing. Instead, after a while the program prints something like "Falling 2144211756." It seems to behave normally when I step through it in a debugger. Why does this happen, and how should the loop be written?

3 Answers

Answered By QuietLantern3 On

Your comparison itself is consistent with the values you chose: y_pos starts at 20 and ground is 200, so y_pos >= ground is initially false. Because you subtract 5 on every iteration and never break, the program eventually reaches an invalid integer range. For a test where the ball falls toward a ground value of 200, you could write something like `while (ball.y_pos < ball.ground) { ball.y_pos += ball.velocity; }`, depending on which direction represents downward movement in your coordinate system.

Answered By SilverKite26 On

The debugger can make this look different because stepping through the program changes its timing and makes it easier to inspect intermediate values; it does not fix the underlying infinite loop. Also, printing every iteration may make the behavior appear normal simply because you can see y_pos decreasing. Make the loop terminate explicitly, for example with `while (ball.y_pos > -100)`, or stop when the ball reaches the ground.

Answered By CrispOrbit8 On

The loop never ends, so y_pos keeps decreasing forever. Eventually it goes below the smallest value that a signed int can represent. In typical builds, the value wraps around to a very large positive number, such as 2144211756, and then y_pos >= ground becomes true. Technically, signed integer overflow in C++ is undefined behavior, so you should not rely on that wraparound. Add a stopping condition and print y_pos before the if statement if you want to observe its changes.

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.