Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Pascal forbid modification of the counter inside the for block?

Is it because Pascal was designed to be so, or are there any tradeoffs?

Or what are the pros and cons to forbid or not forbid modification of the counter inside a for-block? IMHO, there is little use to modify the counter inside a for-block.

EDIT:
Could you provide one example where we need to modify the counter inside the for-block?

It is hard to choose between wallyk's answer and cartoonfox's answer,since both answer are so nice.Cartoonfox analysis the problem from language aspect,while wallyk analysis the problem from the history and the real-world aspect.Anyway,thanks for all of your answers and I'd like to give my special thanks to wallyk.

like image 944
Jichao Avatar asked Jan 15 '10 13:01

Jichao


1 Answers

In programming language theory (and in computability theory) WHILE and FOR loops have different theoretical properties:

  • a WHILE loop may never terminate (the expression could just be TRUE)
  • the finite number of times a FOR loop is to execute is supposed to be known before it starts executing. You're supposed to know that FOR loops always terminate.

The FOR loop present in C doesn't technically count as a FOR loop because you don't necessarily know how many times the loop will iterate before executing it. (i.e. you can hack the loop counter to run forever)

The class of problems you can solve with WHILE loops is strictly more powerful than those you could have solved with the strict FOR loop found in Pascal.

Pascal is designed this way so that students have two different loop constructs with different computational properties. (If you implemented FOR the C-way, the FOR loop would just be an alternative syntax for while...)

In strictly theoretical terms, you shouldn't ever need to modify the counter within a for loop. If you could get away with it, you'd just have an alternative syntax for a WHILE loop.

You can find out more about "while loop computability" and "for loop computability" in these CS lecture notes: http://www-compsci.swan.ac.uk/~csjvt/JVTTeaching/TPL.html

Another such property btw is that the loopvariable is undefined after the for loop. This also makes optimization easier

like image 129
Dafydd Rees Avatar answered Sep 28 '22 02:09

Dafydd Rees