Compilation implications of declaring all scope locals in the beginning as in early C?

165 views Asked by At

I remember hearing that lining up all scope members in the beginning of the block was no longer recommended practice with both C and C++, but does this mean it obstructs the compiler in some way when generating code, or simply that it is no longer necessary to do it, because it is not always convenient? A.K.A is it more efficient for the compiler to generate optimal allocation if locals are declared on demand?

1

There are 1 answers

2
Magnus Hoff On BEST ANSWER

It used to be mandatory to declare locals up front in C, presumably because it is easier to implement a compiler when that is the case.

These days, the compiler is actually "sufficiently advanced" that this does not make any difference for POD types. Because of this, the question boils down to readability and matters of taste in C.


In C++, however, declaring of locals imply things about the execution of the relevant constructor and destructor and it can have bearing on whether or not the compiler will be able to employ certain optimizations. This means that declaring them all at the top is not equivalent to declaring them on demand, rendering your question mostly invalid for C++.

In C++, declare the variables when it is semantically correct for the program you are trying to write. (And on top of that there are also matters of readability and taste)