Should one declare variables (in C) at the begining of a function? I allways declared them before the first use, now i start to question if this is right.
What is the right thing to do /prog/?
If the code you're writing is strict C89, then you should do it at the beginning of the code block. If it's something newer that allows declaring it in random places, then do whatever you wish. I tend to declare it at the beginning, since I like compatibility with a lot of compilers (for example, MS' Optimizing C compiler (MSVC's) tends to be C89-only in its C mode. Of course I could just use C++ mode, but I'd rather not).
but what does the ANSI standard have to say to this?
Name:
Anonymous2010-05-01 17:47
ANSI C89 requires that variables be declared at the beginning of a block. C99 allows variable declaration anywhere, because it caters to sloppy minds.
GNU C also allows declaration anywhere, but unless you need a GNU-specific extension (and you don't), you should be using gcc with the -ansi flag anyway.
Name:
Anonymous2010-05-01 17:52
In my opinion, always at the beginning of a function (for readability) unless there are emergency returns from the function that separate different "steps" implemented. If it's something consuming you need to declare (or malloc) for the next part of an algorithm but you've come to a situation where you have to leave the function because a certain condition hasn't been met, I think it can be useful to declare the "consuming variable" only after the check clears.
Name:
Anonymous2010-05-01 17:52
-ansi flag
does that make gcc use the current ansi standard yet?
>>1
As you can see, you are permitted to declare variables anywhere. However, this is not healthy; if you've got a bunch of new variables coming into play, you ought to have a new function.
Carefully organizing your variables will also help with memory management, which is crucial in C. I'm sure you know that part.
Name:
Anonymous2010-05-02 1:21
>>10
A real programmer knows her machine and compiler well enough to exploit behavioral quirks of different allocation patterns. Reread your SICP.