Equality condition on a double loop variable: unspecified or undefined?

66 Views Asked by At

I would like to get straight on terminology. Consider:

for (double d = 0.0; d != 1.0; d += 0.1)
    cout << d << " ";

If I understand correctly, since double arithmetic is imprecise, this loop can be either finite or infinite. Is this considered unspecified or undefined behavior?

1

There are 1 best solutions below

10
On BEST ANSWER

The behaviour of your program is implementation defined: Different implementations can have different behavior, but they must document it. This is different from unspecified behavior (need not be documented) and undefined behavior (anything goes). See also Undefined, unspecified and implementation-defined behavior.

A common implementation of double is defined by IEEE754. If that standard is followed by your implementation, then that loop will always recover the same output.

Your loop is infinite under IEEE754 - you'll skip over 1.0 and eventually d will grow to such a size where adding 0.1 is a no-op.