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

Rob Kennedy kennedyri+fpc-pascal at gmail.com
Tue Oct 19 16:06:33 CEST 2010


On Tue, Oct 19, 2010 at 12:23 AM, Jürgen Hestermann <
juergen.hestermann at gmx.de> wrote:

> Reimar Grabowski schrieb:
>
>  for (int i = 0;...)
>> Can't see anything wrong. I use declaration of variables inside blocks
>> quite often in Java and C++ but have never missed it in pascal. Please
>> enlighten me. What is so bad about creating temporary variables inside
>> blocks instead of the beginning of a function in a language that supports
>> it?
>>
>
> I never thought about doing such declarations in Pascal.
> Although I would not be against it in general (provided
> that all identifiers have to be different)


That seems like an arbitrary restriction, given that Object Pascal *already*
allows multiple variables to have the same name *and* be declared somewhere
other than the top of the function. Think of exception handlers. I don't
know about everyone else, but my exception variables are all always named e.

I could understand disallowing variables from *shadowing* other local
variables of the same name (it's legal in C, but better compilers warn about
it), but I see no reason for the language to require variables from
different local scopes to have unique names. Write that into your local
coding guidelines and enforce it in code reviews, not the language spec.


> I see one (small) disadvantage:
>
> If you want to know the number of bytes pushed to the stack
> (i.e. in a recursive function) then you don't have the declarations
> at one place anymore but they are spread over the code which would make it
> hard to get an overview.


Definitely small. It's already hard to do since you don't know how much
stack the compiler will allocate for temporary variables. (If the function's
small enough that you *can* predict the compiler's temporary usage, then
it's probably also small enough that you can count all the variable
declarations no matter where they appear.)

-- 
Rob
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20101019/097cdb37/attachment.html>


More information about the fpc-pascal mailing list