HOME BLOG ARCHIVE TAGS

Variable Declaration Placement in C/C++

November 03, 2014

Last week I had an interesting conversation with a good friend from work. It boils down to “I need more freedom when declaring my ANSI C variables”.

For him, variable declaration in C was all about functions, and not about scopes. This is an understandable confusion. In Brazil, Pascal is still taught in college (disclaimer: I hate Pascal with passion).

C89 isn’t very flexible, and variables must be declared at the scope start (GCC may help here; a GNU extension allows declarations at any place).

In the past, it was not uncommon to artificially open curly brace blocks, just for the sake of flexibility. It can be seen in beautiful software (notably when dealing with switch / case constructs).

This helpful mechanism is very simple, and widely adopted in old code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
void func_()
{
    int a = -2;
    int b = -1;

/* (...) */

 {
    int c = 0;
 }
}

Since C99, declaration placement freedom is no longer an issue (one aspect where BASIC was pretty much ahead of its time, albeit in a weird way).

A personal rule that I like to follow - and believe is good programming advice in general - is that a variable should be declared close to where it’s used. In fact, as close as the context makes it possible, without being sloppy (or producing messy code). Some benefits:

  • initialization values become more clear;
  • readability/cohesion is improved;
  • refactoring is made easier;
  • smaller scopes help to catch errors at compile time;
  • compiler optimization may be helped;

Jumping from “old” structured programming paradigm to the “new” OOP demands a conceptual shift (even for the “Pascalers” out there).

In C++, above advice is not even a recommendation. Considering resource acquisition is initialization (RAII), declaring all your variables at the top of a code block is a waste of space and time, because constructors and destructors may be called for no reason.