Declare objects close to use

  • by David Spuler, Ph.D.

Declare objects close to use

The C++ language allows variable declarations to appear almost anywhere within a program. Although the placement of variable declarations may seem unrelated to efficiency, it can have some effect when objects with non-trivial constructors are declared. For efficiency reasons, an object must be declared as close to its first use as possible. In particular, the C style of declaring all variables at the top of a function is often inefficient. Consider the C++ code below:

    void dummy(...)
    {
        complex c; // create object
        if (... ) {
            .... // use c
        }
    }
The complex object is not used if the condition in the if statement is false — the constructor and destructor for the unused object are called needlessly.