Does Location of Variable Declarations Matter?

120 views
Skip to first unread message

jlfo...@berkeley.edu

unread,
Nov 28, 2021, 12:33:43 PM11/28/21
to golang-nuts
Some people put all their variable declarations at the beginning of a function.
Others put them at various places in a function, where the variables are used.

I've always wondered if a variable declaration results in any runtime overhead.
One obvious concern is what happens if a variable declaration is inside a loop.

Cordially,
Jon Forrest


Amnon

unread,
Nov 28, 2021, 6:09:07 PM11/28/21
to golang-nuts
In K&R C back in the 1970s, you had to declare your local variables at the beginning of a function, before any statements.
I think this is the source of the habit of declaring your variables first.

Readability is key here. So it makes sense to declare a statement close to where it is first used,
and limit it to the smallest possible scope where it is needed.

Ian Lance Taylor

unread,
Nov 28, 2021, 8:57:22 PM11/28/21
to Amnon, golang-nuts
On Sun, Nov 28, 2021 at 3:09 PM Amnon <amn...@gmail.com> wrote:
>
> In K&R C back in the 1970s, you had to declare your local variables at the beginning of a function, before any statements.
> I think this is the source of the habit of declaring your variables first.
>
> Readability is key here. So it makes sense to declare a statement close to where it is first used,
> and limit it to the smallest possible scope where it is needed.

I agree, and I'll add that the location of the variable declaration
makes no difference at run time.

Ian


> On Sunday, 28 November 2021 at 17:33:43 UTC jlfo...@berkeley.edu wrote:
>>
>> Some people put all their variable declarations at the beginning of a function.
>> Others put them at various places in a function, where the variables are used.
>>
>> I've always wondered if a variable declaration results in any runtime overhead.
>> One obvious concern is what happens if a variable declaration is inside a loop.
>>
>> Cordially,
>> Jon Forrest
>>
>>
> --
> You received this message because you are subscribed to the Google Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/2734fbdf-ee96-49cb-8666-69c1ac775624n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages