[fpc-pascal] Can variables be declared within a block?

David W Noon david.w.noon at ntlworld.com
Mon Oct 18 19:21:37 CEST 2010


On Mon, 18 Oct 2010 15:42:31 +0200, Florian Klaempfl wrote about Re:
[fpc-pascal] Can variables be declared within a block?:

[snip]
> It's just a matter of readability, e.g. having a variable declared in
> two blocks with the same name can cause you a lot of headache:
> 
> procedure p;
> 
> begin
>   ...
>   begin
>     var i : integer;
>     ...
>     ...
>     ...
>     i:=12341234;
>     ...
>     ...
>     ...
>     ...
>   end;
>   ...
>   ...
>   ...
>   begin
>     var i : integer;
>     ...
>     writeln(i); <--- this i is not the same as above so i does not
> contain 12341234 but it contains probably some garbage.
>   end;

This was not usually a problem in ALGOL 60/68, PL/I or C/C++ -- these
languages have supported short scopes for up to 50 years -- as the
programmer was required to be aware of the different scopes of the
like-named variables.

I still use short scoped variables today, usually in C or C++.  I have
never had any such problems, even going back almost 40 years when I
programmed in ALGOL 60.  All block structured languages require the
programmer to understand the scope of all variables.

Indeed, short scopes can often circumvent name collisions, e.g.

 long some_func(unsigned long arg_1)
 {
    long i;  /* procedure/function scoped */
    unsigned max_iters;
    . . .
    /* calculate "i", "max_iters" and any others */
    . . .
    for (unsigned i = 0; i < max_iters; ++i) /* short scope "i" */
    {
       /* "i" here is distinct from the one at function scope. */
       . . .
    }
    . . .
    return i; /* back to procedure scoped "i". */
 }

Whether it is wise to use such lax naming of variables is open to
debate, but at least C and C++ allow the above.

That said, short scoping was never a part of original Pascal.  I think
Jensen & Wirth omitted it because it made the compiler simpler.
-- 
Regards,

Dave  [RLU #314465]
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
david.w.noon at ntlworld.com (David W Noon)
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: not available
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20101018/68d7b749/attachment.sig>


More information about the fpc-pascal mailing list