When I first started programming I always followed the convention of defining global variables at the top of the file like:
static int a[10];
static int b[10];
void firstFn(void)
{
a[0] = 1;
}
void secondFn(void)
{
b[4] = 2;
}
void thirdFn(void)
{
b[5] = 2;
}
But lately I was working on something where I wanted the definition of a global variable to be grouped with a few functions that operate on that variable defined further down in the file:
static int a[10];
void firstFn(void)
{
a[0] = 1;
}
static int b[10];
void secondFn(void)
{
b[4] = 2;
}
void thirdFn(void)
{
b[5] = 2;
}
Another programmer was reviewing this code and said this was one of his pet peeves. Is there a good reason to stick to the top-defining convention?
Static variables are local to your compilation unit. Their placement makes absolutely no difference, as long as they are declared ahead of their first use in the program.
Although there are no purely technical reasons to keep static declarations at the top of the file, this is a rather widespread convention. I’ve seen it written out explicitly in the coding standards of several companies. When all programmers follow the same convention, the code looks more uniform, and uniformity is a great step toward code maintainability. When someone else opens your file and the code formatting looks familiar, that’s a great plus. So if other colleagues on your team do follow this convention, you should follow it as well.