C Variable declaration in subfunctions

Write your question here.
is there any difference between:

1
2
3
4
5
int Foo(){
 int bar;
 if(Error){return error}
 restofthefunction
}

and
1
2
3
4
5
6
int Foo(){
 if(Error){return error}
 int bar;
 restofthefunction
}


?
I realy not sure...
sorry for the crappy pseudocode, but I think its better than bothering to write some real C code.
Last edited on
In fact they are equivalent except that the second variant is better because variable bar is not defined before its usage.
please give me more info.
and that diference is what I wanna know.

I shuld not have called it 'error'

its more like

If(fo){return 2}
int bar;
rest...

do i get any gain if I declare the variables I need after I check if the funktion aborts anyways?

or is the memory allocated anyways as soon as the function is called? (In that case I wanna keep my code NOT messed up)
As I said there is no any great difference. There could be a difference if variable bar had a user-defined type that results in calling its constructor.
Last edited on
okay thy for the info...
To elaborate on what Vlad said:
In example a, bar is pushed onto the stack unconditionally upon entering Foo.
In example b, bar is only pushed onto the stack if Error is false. Assuming that Error is seldom true, bar will almost always get pushed onto the stack, so there is essentially no difference. Given a good optimizing compiler, bar will get assigned to a register, so there will be no push to the stack in either case.

Now as to style, there are two schools of thought.
1) Some feel that defining variables closest to where they are used is advantageous.
2) Others feel that defining variables at the beginning of the function keeps them all in one place and is easier to maintain.
To each his own.

Topic archived. No new replies allowed.