Examples
Team LiB
Previous Section Next Section

Examples

Example 1: Using a default initial value or ?: to reduce mixing data flow with control flow.



// Not recommended: Doesn't initialize variable


int speedupFactor;


if( condition )


  speedupFactor = 2;


else


  speedupFactor = -1;





// Better: Initializes variable


int speedupFactor = -1;


if( condition )


  speedupFactor = 2;


// Better: Initializes variable


int speedupFactor = condition ? 2 : -1;



The better alternatives nicely leave no gap between definition and initialization.

Example 2: Replacing a complicated computational flow with a function. Sometimes a value is computed in a way that is best encapsulated in a function (see Item 11):



// Not recommended: Doesn't initialize variable


int speedupFactor;





if( condition ) {


  // … code …


  speedupFactor = someValue;


}else {


  // … code …


  speedupFactor = someOtherValue;


}





// Better: Initializes variable


int speedupFactor = ComputeSpeedupFactor();



Example 3: Initializing arrays. For large aggregate types such as arrays, proper initialization does not always mean having to really touch all the data. For example, say you use an API that forces you to use fixed arrays of char of size MAX_PATH (but see Items 77 and 78). If you are sure the arrays are always treated as null-terminated C strings, this immediate assignment is good enough:



// Acceptable: Create an empty path


char path[MAX_PATH]; path[0] = '\0';



The following safer initialization fills all the characters in the array with zero:



// Better: Create a zero-filled path


char path[MAX_PATH] = {'\0' };



Both variants above are recommended, but in general you should prefer safety to unneeded efficiency.

    Team LiB
    Previous Section Next Section