James said:
I just wanted to get some advice on what are the better practices:
1) Should variables be declared at the beginning of a function or just
before they are required?
Under C89 rules, variable declarations in a block
must precede all the executable statements at the same
nesting level. A function body is a block, so all the
"function-wide" variables must be declared at the top.
Note, though, that nested blocks within the function's
outermost block have their own scopes, and can contain
their own variable declarations:
void f(void) {
int x;
...
if (the_witch_is_dead) {
char message[] = "Ding, dong!";
puts (message);
...
}
...
{
double trouble;
trouble = sqrt(toil);
...
}
}
If you have a C99-conforming implementation, you can
mix variable declarations and executable statements, the
only requirement being that the declaration must precede
all the uses.
2) Should all variabled be initiailised immediately after declaration?
No. Initialize those that need initialization, and
leave the others alone. Under C99 rules, a case can be
made for postponing the declaration until a point at which
you know the first value that will be assigned to it, and
declaring and initializing the variable at that point.
Under C89 you might write
void f(void) {
int x;
/* statements not involving x */
x = g(z);
/* statements using x */
}
.... and under C99 this might be a little better as
void f(void) {
/* statements not involving x */
int x = g(z);
/* statements involving x */
}