In my experience, it is customary to place local variable declarations at the beginning of their scope. Several questions in this forum ask whether this needs to be so, and their answers tend to agree on that variables should be declared nearest to their use. This answer suggests a goal of scope minimization, but does not state an opinion on whether declarations should be grouped together or not.
I do think it's cleaner to have declarations (a) grouped together and (b) at the start of their scope. But I also think that interleaving assertions and function calls might help (a) make functions fail faster in an error scenario and (b) add useful restrictions.
Making functions fail faster
Consider test_function_1
defined below:
void test_function_1(const int *const param)
{
assert(NULL != param);
/* (Function declarations.) */
/* (Main logic.) */
}
Assume that the assertion is reasonable: test_function_1
needs param
not to be null. Here, having the assertion precede the declarations helps the function fail faster from an irrecoverable scenario. I have not seen this style before, so I wonder:
Is there a reason not to do this?
Adding useful restrictions
Consider test_function_2
defined below:
void test_function_2(void)
{
const int a = get_a();
function_with_side_effects(a);
const int b = function_affected_by_side_effects();
/* (Main logic. Assume that 'a' and 'b' are used sufficiently.) */
}
Here, having the call to function_with_side_effects
precede the declaration of b
allows us to define b
as a constant. (It is not possible to declare b
as a constant, then call function_with_side_effects
and then define b
with function_affected_by_side_effects
.) If we do things the traditional way and declare b
first, not as a constant, then we lose the constraint that is so useful to us.
Is there a reason not to do this?