[QUESTION] Regarding non-infinite loops

Thank you for all your help.
Sorry for the simple question, but I personally think that the following code may be beneficial to avoid infinite loops, although there are side effects that are affected by machine specs, etc.

#[test]
fn test_not_infinite_loop() {
    //for i in 2 as i128.. { // #[allow(clippy::unnecessary_cast)]
    for i in 0_u128.. {
        println!("{i}");
        if i >= u64::MAX.into() {
            break;
        }
    }
}

However, I can't think of any specific usage scenario, so if you have any precedents, please let me know.

P.S.
I am also thinking that it might be simpler to describe it in macro form.

Two problems with your plan:

  • An infinite loop (that isn't on purpose for a server or such) may be bad, but arbitrarily ending a loop at some limit (without panicking or returning any error) is worse, because it gives you a wrong answer without complaint. So, if a limit is hit, break is not usually the right thing to do about it. (Except for e.g. numerical approximation algorithms where stopping early just gives you a worse approximation.)

  • u64::MAX is far too large a limit for any loop; a program will spend years just counting up to it and centuries if the loop contains any other work. In practice, limits must be chosen for the particular application; otherwise they will be either too small for the real work or too large to cancel a runaway task in a reasonable time.

So, there cannot be any automatic, "one size fits all" loop limiting.

3 Likes

Thank you for your reply.

I learned a lot from your two points.

This kind of break should not be done.

I will keep them in mind and continue learning.

Not years, more than a century. Assuming a 4 GHz CPU, it will take ~146 years (2^64/(4*10^9)/3600/24/365) and it's not even accounting for cost of jump instructions.

2 Likes

I wanted my claim to hold up for a few more years itself! :slight_smile: Some CPU might be capable of tricks that allow it to compute multiple iterations per clock cycle. Or something else new will come along.

2 Likes

I do wish we had some sort of checking for this, but as far as I know doing and specifying that well is still an open computer-science problem. (Especially since Rice's theorem - Wikipedia is brutal.)

It would be pretty cool to have a general "hey, you need to annotate anything that's worse than linearithmic in its inputs", but I have no idea how to make that work :upside_down_face:

1 Like