Hacker News new | ask | show | jobs
by xenomachina 1406 days ago
> In C, you used to have to declare all local variables at the top of the function rather than throughout the body.

This is true, but support for block-scoped (as opposed to function-scoped) variable declarations was added to C a long time ago. Every version of ANSI C supports them, and this stack exchange answer, https://softwareengineering.stackexchange.com/a/300274/19196, suggests that support was added to K&R C since at least 1978.

1 comments

Hmm, interesting! I might be remembering wrong, but I remember within the last decade being told by a coworker that it was required for proper Windows support, but maybe that was just an old version of Visual Studio from XP or something that no longer needs to be supported.
And C99 allows you to declare variables anywhere in the function (much like C++).
I remember that the reason my coworker had said that they couldn't use local variables declared anywhere in functions for their Windows code was due to not supporting C99, but maybe that was just due to some external constraint rather than a Windows-specific one (like some customer needing them to support pre-C99 code or something).
Even C89 supports block-level variable declarations. I think many C programmers are unaware of this, though, and mistakenly think that declarations are function-level only.