Hacker News new | ask | show | jobs
by andystanton 2726 days ago
Question for C experts, the article states:

C takes the middle road -- variables may be declared within the body of a function, but they must follow a '{'. More modern languages like Java and C++ allow you to declare variables on any line, which is handy.

I know this is not the case in C11 for example, but is there a compile-time speed-up when declaring variables in this way, or any other benefit?

4 comments

Old C compilers would first parse declarations, then allocate space on the local stack (usually by subtracting the number of bytes needed from the stack pointer), and go on to compile code, knowing that - from that point on - there's a well defined stack structure (and very often in those days, even a constant offset from the "frame pointer" or "base pointer" which would be copied from the stack pointer at that point)

Introducing additional variables later, means that if you emit code "as you go", you'll be less efficient - which makes no difference today, but was a big thing in the days C was designed; Most compilers back then were single pass, emit-as-you-go. There are relatively simple ways to deal with that even under the single-pass constraint, but in those days and the common compiler construction techniques prevalent at the time, it was considered harder.

There was always an issue of fixups with scope-exiting control transfer like break and goto - however, they are simpler, and don't harm emit-as-you-go compilation to the same extent.

On the other hand, one nice thing about C compilers is that they are _fast_. I always inwardly shudder when I see a C++ file including Boost, because I know the compiler is going to have to chew on it for several seconds every time there's a change.
This slowness isn't the result of where you can declare variables though!
In assembler, the function prologue has to set up the stack frame with enough space to store local variables. Having all local variable declarations come at the beginning of the function was an extension of that - keeping C closer to assembler and perhaps making compilation conceptually easier. With modern optimizing compilers, though, we're not necessarily directly translating to assembler line for line, and might optimize out some variables entirely, so it doesn't matter as much.

EDIT: Looks like beagle3 beat me to it while I got coffee.

C has permitted mixing declarations and statements since the 1999 standard.
I suspect it may have helped very slightly with the parsing in early compilers to not mix declarations and other statements, but with SSA-based compilation which is quite common now, it doesn't matter where you declare variables as long as you do so before you use them.