Search code examples
c++cknuth

C for loop implemented differently than other languages?


I read the following in a review of Knuth's "The Art of Computer Programming":

"The very 'practicality' means that the would-be CS major has to learn Kernighan's mistakes in designing C, notably the infamous fact that a for loop evaluates the for condition repeatedly, which duplicates while and fails to match the behavior of most other languages which implement a for loop."

(http://www.amazon.com/review/R9OVJAJQCP78N/ref=cm_cr_pr_viewpnt#R9OVJAJQCP78N)

What is this guy talking about? How could you implement a for loop that wasn't just syntactic sugar for a while loop?


Solution

  • Consider this:

    for i:=0 to 100 do { ... }
    

    In this case, we could replace the final value, 100, by a function call:

    for i:=0 to final_value() do { ... }
    

    ... and the final_value-function would be called only once.

    In C, however:

    for (int i=0; i<final_value(); ++i) // ...
    

    ... the final_value-function would be called for each iteration through the loop, thus making it a good practice to be more verbose:

    int end = final_value();
    for (int i=0; i<end; ++i) // ...