C++.Coding.Standards.1918.Rules.Guidelines [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

C++.Coding.Standards.1918.Rules.Guidelines [Electronic resources] - نسخه متنی

Herb Sutter, Andrei Alexandrescu

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید


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.


/ 521