Search code examples
language-agnosticreturninfinite-loop

Infinite loop with a return statement - bad style but unavoidable?


I have an algorithm that will keep running until a test is passed, at which point a value will be returned. The way I am currently implementing it is with an infinite loop, but I am wondering if there is a way to do it without using the infinite loop (to satisfy the purists). The pseudocode is as follows

while (true) {
    choose initialNode at random
    G = constructComplicatedGraphFromNode(initialNode)
    if G satisfies some property
        return G
    end
}

Solution

  • The forgotten do-while? Or for (;;) { }. In principle the original form is not bad-style IMHO, as some non-linear behaviour is okay.

    do {
        choose initialNode at random
        G = constructComplicatedGraphFromNode(initialNode)
    } while (! G satisfies some property);
    return G
    

    Bad style is relying on random picks to terminate the loop however.