I see a lot of code with variables declared right after the function, but when I post something like that people end up mad and say it is better to declare them when they are used.
I assume this all compiles to the same executable, so it is simply a matter of style. As far as I can tell, pretty much all C code (99.9% that I’ve seen) declares them near the beginning and this is how it has been done for many years.
So why do people keep suggesting that they are declared closer to the block that uses them?
1
You must be looking at old code or code written only on Windows. K&R C and C89 required variables to be declared at the beginning of a block. C99 allows variables to be declared anywhere before they are used. The GNU C compiler has supported flexible declaration as a non-standard extension for some time. Microsoft didn’t have any support for the C99 standard until Visual Studio 2013
6
You must be looking at very old code, code written by people that are either not up to date on their skills, or code written by people that enjoy writing Pascal in C.
Older versions of the C language spec (C89 and prior) required the declarations to be immediately following the opening brace, but since then modern compilers have eliminated that requirement.
See https://stackoverflow.com/questions/14324546/why-do-the-older-c-language-specs-require-function-local-variables-to-be-declare for more information.
1