Skip to main content

#8. Define variables as close as possible to where they are used

Define variables as close as possible to their first use. Prefer variables with the most local scope as possible.

Inside a function body, at run time, a variable begins to exist once the code execution reaches the point where it is defined - not the point where it is only declared. (The Stack Overflow question What is the difference between a definition and a declaration? will help you understand the difference between a variable declaration and a variable definition. See the Answer by sbi.)

It benefits the readability of your code that you keep functions short and well structured. To achieve this, It is a key factor that every concept is limited to the exact scope where it belongs to. Define, initialize and use each variable exactly where it is needed, not any earlier. By following this simple guideline you will write code which is more readable, contains less defects, and is easier to debug.

Refactoring a function body is one of the most common tasks in software engineering. What was before in one function could be separated into several functions in the future. If you limit the scope of each variable to exactly the needed one, you will make this process much easier.

If you have seen code in which a variable of a certain type is reused inside the function body for two or three different things, just to save some bytes, please forget about it. Use each variable exactly once - don't define variables which are never used, and don't use the same variable for several different things.

A local variable has only the scope of the braces which contain it. Because of this, a function may contain some inner block of code in which you define a variable, say, int i = 0;. Later in the same function you may have a later block of code in which you will be allowed to create another variable with the same type and name: int i = 0;. These are different variables, which totally disjoint scopes. This is perfectly correct. However, prefer not doing it. It is error prone and it hurts readability to have two different variables with the same name so close to each other. In fact, "i" is not a very expressive name - you should be able to come up with better names for both variables, names which say more about their meaning.

Bibliography

[McConnell 2004]
Steve McConnell: Code Complete, 2nd Edition, Microsoft Press, 2004.

This book discusses variable initialization in section 10.3: "Guidelines for initializing variables" (page 242). Scope is discussed in section 10.4: "Scope" (page 244). And the title of section 10.8 speaks for itself: "Using each variable for exactly one purpose" (page 255).

[Meyers 1998-1]
Scott Meyers: Effective C++: 50 specific ways to improve your programs and designs, 2nd Edition, Addison Wesley, 1998.

Meyers advises us to "Postpone variable definitions as long as possible" in Item 32 of this book (page 135).

[Sutter-Alexandrescu 2004]
Herb Sutter, Andrei Alexandrescu: C++ Coding Standards. 101 Rules, Guidelines and Best Practices, Addison Wesley, 2004.

The C++ Coding Standards suggested in this book include Item 18, "Declare variables as locally as possible" (page 35).



Comments

Popular posts from this blog

#11. Don't use syntactic overloading

Syntactic overloading (or function overloading) is a C++ feature which allows a class to have several functions with the same name, but with different parameters. To say "Don't use syntactic overloading" is the same as to say "Don't give the same name to different functions".

class C
{
    ...
    void add(int i);
    void add(double d);
    void add(C other);
    ....
}

When you write this client code:

C c;
c.add(x);

The compiler will call the appropiate version of the funcion add, depending on the type of x.

This is what syntactic overloading is. It is called syntactic overloading to distinguish it from semantic overloading 8more properly called dynamic binding), which is the one that happens when you use inheritance and polymorphism.

Syntactic overloading may seem useful at first sight, but it has lots of drawbacks for no real advantage. It just can go wrong in too many ways.

Code is more readable without syntactic overloading. One name for each thing, different n…

#2. Make all type conversions explicit

Assignments, function calls and expressions in general should not contain implicit type conversions. All type conversions should be explicit.

Type conversions should be isolated in their own line, which should consist only of the assignment of the result of the type conversion to a variable of the target type.

A statement should not mix type conversion with other operations. For example, if you need to convert an object to one of another type to pass it as a function parameter, do not do it in the function call itself; instead, do it in a separate instruction in the previous line.
Type conversion occurs when an entity of type A is, well, converted to an entity of type B. This may occur in function calls, expressions using operators, or assignments.
An explicit type conversion is one which you can read in the code. An implicit type conversion is one which does not appear in the source code, but is done automatically when the software is executed.
Making all type conversions explicit he…

#10. Choosing the right loop structure

C++ has three loop instructions: for, while and do ... while. To choose wisely among them, you need to know what their differences are.
1) for A for loop makes sense when you repeat an action for a known number of times, or for all the elements of a known set.

This is the syntax of a forloop:

for (initialization; condition; expression)
{
    statement
}

statement is actually a compound statement, that is, a block of code. This is called the body of the loop. In contrast, the initialization, condition and expression together are called the header of the loop. The initialization is a single statement which ends at the semicolon I wrote after it. The condition is a boolean expression. The expression is a statement. It should be a single statement which modifies one variable which is involved in the condition (see #guideline #5).

The initialization is performed. Then, the condition is evaluated. Then, two things can happen. If the condition is false, the code jumps right after the for statemen…