开发者

Infinite Loops: int vs. float

I'm working on a homework assignment and am probably psyching myself out about this thing a little too much, so I am just seeking some input. Here's 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 one where it is an int. The question is are these infinite loops.

I am thinking that when x is an 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.

Am I close?


The behavior when a signed integer is increased beyond its limit is undefined. So the loop may end or it may be infinite. Or it may crash (or the loop may never run at all). Or as some C gurus like to say, demons may fly out of your nose - though personally I doubt any compiler implementor would go through the trouble of implementing nasal demon functionality.

As far as floating point values are concerned, you are correct that it will be an infinite loop.


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

Some compilers (like GCC) actually implement so called strict value semantics, which means that the compiler takes advantage of that undefined behavior for optimization purposes. In your specific example, the compiler might immediately generate a straightforward infinite loop, i.e. a loop that doesn't have any termination condition at all.


You are indeed correct, integers will overflow to negative values (as long as they're signed) so the loop will end, and floats will stick to "+infinity" which is always greater than any number except NaN.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜