Does it terminate?

Published on 2010-09-21 00:00:00

Here’s a little puzzler: is the following C code guaranteed to terminate?

void func()
{
    double best, value;
    int changed, k;

    best = 0.0;
    changed = 1;
    while (changed) {
        changed = 0;
        for (k = 0; k < 3; ++k) {
            /*
             * Compute a floating-point result, for each k.
             * It always returns exactly the same floating point number
             * for given k.
             */
            value = compute_value(k);
            if (value > best) {
                best = value;
                changed = 1;
            }
        }
    }
}

Spoiler below the fold.


Show spoiler...

Comments

blog comments powered by Disqus