Search code examples
c++ccompiler-construction

Why earlier versions of C made it mandatory to declare variables in the beginning?


I have been going through a bit of history of C, and I find that in earlier versions of C, like in C89 standard, it is mandatory to declare variables at the beginning of a block.

But I also find there are some relaxations from C99 standard specification, where variable can be declared anywhere before it is used.

My question is why the earlier versions made it mandatory? my emphasis is to know if there was any technical difficulties in designing the compiler at those days, that prevented them identifying declarations at any point.

Also, with a compiler design perspective I understand, with such a restriction in C89, it is easy to handle variable declarations and usage with the help of an intermediate file to store the mappings. But are there methods that can handle the case without using an intermediary file, say some memory based storage?.


Solution

  • If the compiler sees a consolidated list of all the local/automatic variables up front, it can immediately work out the total amount by which to move the stack pointer to reserve stack memory for them - just one operation on the stack pointer. If it handles the variables in dribs and drabs as they're encountered in the function, moving the stack pointer incrementally, then there ends up being more opcodes dedicated to stack setup and stack pointer updates. It's important that the stack pointer be up to date whenever a further function call's performed. Newer compilers do a tiny bit of extra work to patch back in the amount by which to move the stack pointer after all the function's been considered. (I'd hazard that the effort's so minimal that the early Standard was shaped more by the conceptual appeal of knowing what to do up front than the effort of being more flexible, but if you just want to get something working - why make extra efforts?)