0

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
  • I don't know of anyone who declares their variables right after a function. Commented Aug 6, 2014 at 3:38

2 Answers 2

3

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
  • But which is better? Commented Aug 6, 2014 at 3:54
  • 2
    @floopdagoop: which is better is a question different than what you asked. programmers.stackexchange.com/questions/56585/… Commented Aug 6, 2014 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? Commented Aug 6, 2014 at 3:59
  • Or, isolating everything into neat functions? Or, using an editor that allows easy lookup of definitions? Commented Aug 6, 2014 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. Commented Aug 6, 2014 at 4:47
1

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
  • "modern compilers have eliminated that requirement" ...if your code has to build under Visual Studio, "modern" only means "2013 or newer" :P Commented Aug 6, 2014 at 8:58

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.