lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


David Given wrote:
...
As another data point:

C++ (and now C99) allows you to declare loop variables inside loop statements:

for (int i=0; i<10; i++)
{
	printf("%d\n", i);
}

It's interesting to note that old versions of the standard decreed that the scope of the loop variable extended until the end of the enclosing scope; that is, it was equivalent to:

int i;
for (i=0; i<10; i++)
	...

However, the standard then changed so that the scope was limited to the for() block only.

I've been trying to track down the reasons why they changed their minds over this, because their reasoning might be informative... but I can't. But they obviously thought it was important enough to actually make an incompatible change to the standard.

All they did was change the semantics from this:

    int i;
    for (i=0; i<10; i++)
        ...

to this:

    {
        int i;
        for (i=0; i<10; i++)
            ...
    }

Since the for and while loops test their expressions before the block, this all works well and is obvious. Repeat loops are oddballs because they don't test their expression until the end of the loop. So the scope is important inside the block.

Personally, I don't ever use repeat loops because I find that they obfuscate the algorithm, much like the lack of continue :-)

--
chris marrin                ,""$,
chris@marrin.com          b`    $                             ,,.
                        mP     b'                            , 1$'
        ,.`           ,b`    ,`                              :$$'
     ,|`             mP    ,`                                       ,mm
   ,b"              b"   ,`            ,mm      m$$    ,m         ,`P$$
  m$`             ,b`  .` ,mm        ,'|$P   ,|"1$`  ,b$P       ,`  :$1
 b$`             ,$: :,`` |$$      ,`   $$` ,|` ,$$,,`"$$     .`    :$|
b$|            _m$`,:`    :$1   ,`     ,$Pm|`    `    :$$,..;"'     |$:
P$b,      _;b$$b$1"       |$$ ,`      ,$$"             ``'          $$
 ```"```'"    `"`         `""`        ""`                          ,P`
"As a general rule,don't solve puzzles that open portals to Hell"'