More Books
C++ Gotchas: Avoiding Common Problems in Coding and Design
Main Page
Table of content
Copyright
Addison-Wesley Professional Computing Series
Preface
Acknowledgments
Chapter 1. Basics
Gotcha #1: Excessive Commenting
Gotcha #2: Magic Numbers
Gotcha #3: Global Variables
Gotcha #4: Failure to Distinguish Overloading from Default Initialization
Gotcha #5: Misunderstanding References
Gotcha #6: Misunderstanding Const
Gotcha #7: Ignorance of Base Language Subtleties
Gotcha #8: Failure to Distinguish Access and Visibility
Gotcha #9: Using Bad Language
Gotcha #10: Ignorance of Idiom
Gotcha #11: Unnecessary Cleverness
Gotcha #12: Adolescent Behavior
Chapter 2. Syntax
Gotcha #13: Array/Initializer Confusion
Gotcha #14: Evaluation Order Indecision
Gotcha #15: Precedence Problems
Gotcha #16: 'for' Statement Debacle
Gotcha #17: Maximal Munch Problems
Gotcha #18: Creative Declaration-Specifier Ordering
Gotcha #19: Function/Object Ambiguity
Gotcha #20: Migrating Type-Qualifiers
Gotcha #21: Self-Initialization
Gotcha #22: Static and Extern Types
Gotcha #23: Operator Function Lookup Anomaly
Gotcha #24: Operator '->' Subtleties
Chapter 3. The Preprocessor
Gotcha #25: '#define' Literals
Gotcha #26: '#define' Pseudofunctions
Gotcha #27: Overuse of '#if'
Gotcha #28: Side Effects in Assertions
Chapter 4. Conversions
Gotcha #29: Converting through 'void *'
Gotcha #30: Slicing
Gotcha #31: Misunderstanding Pointer-to-Const Conversion
Gotcha #32: Misunderstanding Pointer-to-Pointer-to-Const Conversion
Gotcha #33: Misunderstanding Pointer-to-Pointer-to-Base Conversion
Gotcha #34: Pointer-to-Multidimensional-Array Problems
Gotcha #35: Unchecked Downcasting
Gotcha #36: Misusing Conversion Operators
Gotcha #37: Unintended Constructor Conversion
Gotcha #38: Casting under Multiple Inheritance
Gotcha #39: Casting Incomplete Types
Gotcha #40: Old-Style Casts
Gotcha #41: Static Casts
Gotcha #42: Temporary Initialization of Formal Arguments
Gotcha #43: Temporary Lifetime
Gotcha #44: References and Temporaries
Gotcha #45: Ambiguity Failure of 'dynamic_cast'
Gotcha #46: Misunderstanding Contravariance
Chapter 5. Initialization
Gotcha #47: Assignment/Initialization Confusion
Gotcha #48: Improperly Scoped Variables
Gotcha #49: Failure to Appreciate C++'s Fixation on Copy Operations
Gotcha #50: Bitwise Copy of Class Objects
Gotcha #51: Confusing Initialization and Assignment in Constructors
Gotcha #52: Inconsistent Ordering of the Member Initialization List
Gotcha #53: Virtual Base Default Initialization
Gotcha #54: Copy Constructor Base Initialization
Gotcha #55: Runtime Static Initialization Order
Gotcha #56: Direct versus Copy Initialization
Gotcha #57: Direct Argument Initialization
Gotcha #58: Ignorance of the Return Value Optimizations
Gotcha #59: Initializing a Static Member in a Constructor
Chapter 6. Memory and Resource Management
Gotcha #60: Failure to Distinguish Scalar and Array Allocation
Gotcha #61: Checking for Allocation Failure
Gotcha #62: Replacing Global New and Delete
Gotcha #63: Confusing Scope and Activation of Member 'new' and 'delete'
Gotcha #64: Throwing String Literals
Gotcha #65: Improper Exception Mechanics
Gotcha #66: Abusing Local Addresses
Gotcha #67: Failure to Employ Resource Acquisition Is Initialization
Gotcha #68: Improper Use of 'auto_ptr'
Chapter 7. Polymorphism
Gotcha #69: Type Codes
Gotcha #70: Nonvirtual Base Class Destructor
Gotcha #71: Hiding Nonvirtual Functions
Gotcha #72: Making Template Methods Too Flexible
Gotcha #73: Overloading Virtual Functions
Gotcha #74: Virtual Functions with Default Argument Initializers
Gotcha #75: Calling Virtual Functions in Constructors and Destructors
Gotcha #76: Virtual Assignment
Gotcha #77: Failure to Distinguish among Overloading, Overriding, and Hiding
Gotcha #78: Failure to Grok Virtual Functions and Overriding
Gotcha #79: Dominance Issues
Chapter 8. Class Design
Gotcha #80: Get/Set Interfaces
Gotcha #81: Const and Reference Data Members
Gotcha #82: Not Understanding the Meaning of Const Member Functions
Gotcha #83: Failure to Distinguish Aggregation and Acquaintance
Gotcha #84: Improper Operator Overloading
Gotcha #85: Precedence and Overloading
Gotcha #86: Friend versus Member Operators
Gotcha #87: Problems with Increment and Decrement
Gotcha #88: Misunderstanding Templated Copy Operations
Chapter 9. Hierarchy Design
Gotcha #89: Arrays of Class Objects
Gotcha #90: Improper Container Substitutability
Gotcha #91: Failure to Understand Protected Access
Gotcha #92: Public Inheritance for Code Reuse
Gotcha #93: Concrete Public Base Classes
Gotcha #94: Failure to Employ Degenerate Hierarchies
Gotcha #95: Overuse of Inheritance
Gotcha #96: Type-Based Control Structures
Gotcha #97: Cosmic Hierarchies
Gotcha #98: Asking Personal Questions of an Object
Gotcha #99: Capability Queries
Bibliography

Gotcha #16: for Statement Debacle

C++ has several places where it's legal to declare a variable in a restricted scope that's not simply a nested block. For example, it's possible to declare a variable in the condition of an if-statement. The variable will be available in the statements controlled by the condition, both the "true" and "false" branches:

if( char *theName = lookup( name ) ) { 
   // do something with name . . .
}
// theName is out of scope here

Formerly, the variable would have been declared outside the if-statement, with the unfortunate consequence that it would still be hanging around, looking for trouble, after we'd finished with it:

char *theName = lookup( name ); 
if( theName ) {
   // do something with name . . .
}
// theName is still available here . . .

It's generally a good idea to restrict the scope of a variable to the region of the program in which it's used. Under maintenance, for reasons beyond my ability to understand, these variables tend to be reused for some wildly different purpose. The effect on documentation and maintenance is, shall we say, "negative." (See also Gotcha #48.)

theName = new char[ ISBN_LEN ]; // need buffer for ISBN 

The same is true of the for-statement; an iteration variable can be declared as the first part of the statement:

for( int i = 0; i < bufSize; ++i ) { 
   if( !buffer[i] )
       break;
}
if( i == bufSize ) // was legal, now illegal, i not in scope
   // . . .

This was legal C++ for many years, but the scope of the iteration variable has changed. Formerly, the scope of the variable extended from the point of its declaration (just before the initializer; see Gotcha #21) to the end of the block that contains the for-statement. Under the new semantics, the scope is restricted to the for-statement itself. Although most C++ programmers believe that the change makes good sense in most ways—it's more orthogonal to the rest of the language, makes it easier to optimize loops, and so on—it's something of a pain in the neck to go back and repair all the older uses of for.

Sometimes it's more than just a pain in the neck. Consider the possibility of a quiet change in meaning:

int i = 0; 
void f() {
   for( int i = 0; i <bufSize; i++ ) {
       if( !buffer[i] )
       break;
   }
   if( i == bufSize ) // file scope i!
       // . . .
}

Fortunately, this kind of error is rare, and most quality compilers will warn about the condition. Take the warning seriously (and don't turn off warnings), and try to avoid hiding outer scope names in inner scopes. And lay off the global variables. (See Gotcha #3.)

Strangely, the most damaging effect of the scope change in the for-statement has been its effect on how some C++ programmers write their for-statements:

int i; 
for( i = 0; i < bufSize; ++i ) {
   if( isprint( buffer[i] ) )
       massage( buffer[i] );
   // . . .
   if( some_condition )
       continue;
   // . . .
}

This is C code, not C++ code. It does have the advantage of having the same meaning under both the old and new for-statement semantics, but consider what's been lost. First, the iteration variable remains in force after the for-statement. Second, the variable i is not initialized. Neither of these is an issue when the code is first written, but under maintenance, less experienced programmers may attempt to use the uninitialized i before the for-statement as well as after, when the original designer had hoped i would quietly disappear.

Another problem is that the issue drives some programmers away from the for-statement entirely:

int i = 0; 
while(  i < bufSize ) {
   if( isprint( buffer[i] ) )
       massage( buffer[i] );
   // . . .
   if( some_condition )
       continue; // oops!
   // . . .
   ++i;
}

The problem here is that the while-statement is not equivalent to the for-statement. For example, if there's a continue within the body of the loop, the program will suffer a change in meaning that may not be easily detected. In this case the code will infinite loop, which is usually an indication of some sort of problem. We aren't always so lucky.

If you're fortunate enough to deal exclusively with platforms that support the new for-statement semantics, the best procedure for dealing with the change in meaning of the for-statement is to embrace the change as soon as your platforms allow.

Unfortunately, it's perhaps more often the case that code must be compiled on different platforms, with contradictory for-statement semantics. It may seem logical in this case to write for-statements that have the same meaning under either translation:

int i; 
for( i = 0; i < bufSize; ++i ) {
   if( isprint( buffer[i] ) )
       massage( buffer[i] );
   // . . .
}

However, I recommend instead that all for-statements be written to the new semantics. To avoid problems with the scope of the iteration variable, the for-statement can be enclosed in a block:

{for( int i = 0; i < bufSize; ++i ) { 
   if( isprint( buffer[i] ) )
       massage( buffer[i] );
   // . . .
}}

This is hideous enough that it will surely be noticed and removed when no longer needed. It also has the advantage of encouraging the original programmer to write the for-statement to the new semantics, avoiding the need to perform that bit of additional maintenance later.