Endless loops: int vs. float

I'm working on a homework assignment and probably know too much about this stuff, so I'm just looking for a job. Here is the basic code:

for(x = 100; x > 0; x = x + x) { sum = sum + x; 

There are two versions: one where x is a float and the other is int . The question is whether these are endless loops.

I think that when x is int , it will eventually overflow, making it less than zero, and the loop will stop. When x is a float , x will reach infinity, and the loop will be infinite.

I close?

+6
source share
3 answers

The behavior when a signed integer is greater than its limit is undefined. Thus, the cycle may end or may be infinite. Or it can cause a crash (or the loop can never start at all). Or, as some C gurus say, demons can fly out of your nose, although I personally doubt that any compiler developer will handle the problem of implementing the functions of a nose daemon.

As for floating point values, you are right that it will be an infinite loop.

+8
source

When declaring integer overflows, the behavior is undefined. Expecting x become negative is naive at best.

Some compilers (like GCC) actually implement what are called strict value semantics, which means that the compiler uses this undefined behavior for optimization purposes. In your specific example, the compiler can immediately generate a simple infinite loop, i.e. A cycle that does not have any completion conditions at all.

+3
source

You are really right, integers will overflow to negative values ​​(until they are signed), so the loop will end, and the float will adhere to + infinity, which is always greater than any number except NaN .

Edit: I stand fixed, the int version makes the loop endlessly (on some compilers due to their assumptions): http://ideone.com/HZkht

+2
source

Source: https://habr.com/ru/post/890268/


All Articles