Re: In which scope should variables be declared?
- From: gordonb.joep4@xxxxxxxxxxx (Gordon Burditt)
- Date: Fri, 23 Sep 2005 20:33:48 -0000
In article <1127506658.746576.56720@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>,
elzacho <elzacho@xxxxxxxxx> wrote:
>I would like to (and commonly do) define my variables in the most
>specific scope I can. For example...
>
>int foo(int a, int b, int c)
>{
> /* don't declare temp here if we can help it */
> ...
>
> for (i = 0; i < max; i++)
> {
> /* declare here */
> int temp;
> ...
> /* use temp */
If you expect temp to have its value survive from one interation
of this loop to the next, DON'T declare it inside the for loop.
Logically, the variable is destroyed and re-created each iteration
of the loop.
> }
>}
>
>But my concern is, does the declaration take up cpu time?
Maybe.
>One can
>imagine that temp could be a huge array or max could be a large number.
Does adding a million take more time than adding one?
> In this case, if the declaration maps to any cpu time when compiled,
>this could lead to a significant performance drop.
Standard C does not guarantee that a program has performance to drop.
If you can't measure it, don't worry about it. If you haven't got
time to measure it, you don't have time to worry about whether it
takes CPU time.
>So, is there a difference in the machine code between declaring all of
>your variables at outer most scope or inner most scope?
Possibly. If you declare the variables at the innermost scope,
those in different blocks may overlap each other, making the offsets
different. That's a difference in the machine code. I didn't say
it was a difference in the execution time.
>My impressions
>on C are that it makes does not impose how this is handled, rather that
>this is a compiler issue, but I am not sure how much the standards
>dictate this. Thought I would pass it by some experts.
C rarely dictates HOW anything is handled. It's just supposed to work
as indicated.
Gordon L. Burditt
.
- References:
- In which scope should variables be declared?
- From: elzacho
- In which scope should variables be declared?
- Prev by Date: In which scope should variables be declared?
- Next by Date: Re: In which scope should variables be declared?
- Previous by thread: In which scope should variables be declared?
- Next by thread: Re: In which scope should variables be declared?
- Index(es):
Relevant Pages
|