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?

marked as duplicate by Robert Harvey, user40980, gnat, Kilian Foth, Wayne Molina Aug 6 '14 at 17:10

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • I don't know of anyone who declares their variables right after a function. – Robert Harvey Aug 6 '14 at 3:38

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

  • But which is better? – floopdagoop Aug 6 '14 at 3:54
  • 2
    @floopdagoop: which is better is a question different than what you asked. programmers.stackexchange.com/questions/56585/… – whatsisname Aug 6 '14 at 3:57
  • 2
    The reason the standard changed was because the consensus was that declaring variables as near as possible to their first use made code more readable. Consider: you are looking at an assignment to 'foo'. Which do you think would be more disruptive to your train of thought: looking up two lines to see that 'foo' is an int, or scrolling up a screen and a half for the same information? – Charles E. Grant Aug 6 '14 at 3:59
  • Or, isolating everything into neat functions? Or, using an editor that allows easy lookup of definitions? – floopdagoop Aug 6 '14 at 4:15
  • The code does not necessarily have to be old or only for Windows. New code is still often written in C89 if it should be portable. – Jan Hudec Aug 6 '14 at 4:47

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.

  • "modern compilers have eliminated that requirement" ...if your code has to build under Visual Studio, "modern" only means "2013 or newer" :P – detly Aug 6 '14 at 8:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.