Building on this example and others found elsewhere we have two types of loops, definite and indefinite:

definite being a loop that has its number of iterations known before it is executed. E.g. a for loop:

for x in range(1,10):

and indefinite loops which don't have the number of iterations known before it is executed. E.g. this while loop:

while answer <> "Yes":
    answer = input("are you an idiot?")

I'm checking some teaching materials that have an example of a while loop that looks definite to me as by looking at the code you know exactly when it is going to end:

number = 1
while  number <= 10:
    number = number +1

Is this example a definite loop even though we have to do a little work to work out the for loop equivalent?


1 Answer 1


Yes, this is definite loop, as long as you (or your compiler for that matter) can infer number of passes.
In some languages (like C), 'for' is a transformation that expands during compilation to 'while' construction like you have shown. Compiler would infer number of steps during optimisation phase, when you have provided constant expression loops of any kind, but will not infer that from variable expressions.

  • $\begingroup$ In C, C++ or related languages, “for” is most definitely NOT a macro, and the number of iterations is generally not known. $\endgroup$
    – gnasher729
    Apr 29, 2019 at 14:37
  • $\begingroup$ @gnasher729 it is a transformation, not a macro as in #define macro, true so I have edited post. Also, for constant expressions compiler infers number of passes and I have nowhere mentioned that this is always the case (like variable expressions), but corrected it. Standard says exactly about for -> while transform and it was in the early days semantically equivalent, now it may differ (in new C++ for example), but still compilers do use subseted IL, so it is effectively the same. If you are still seeing issues, let me repair them. $\endgroup$
    – Evil
    Apr 29, 2019 at 15:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.