Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Take Charge and Initialize Your Own Data


nlike most other programming languages, C++ by default doesn't initialize automatic variables. Consequently, uninitialized auto variables and aggregates have an indeterminate value.

Due to insufficient familiarity with the correct syntax of aggregate initialization, many programmers either misuse library functions such as memset() or forgo initialization altogether, thereby incurring unnecessary performance overhead, future maintenance problems, and potential bugs.

Properly initialize all POD ("Plain Old Data") auto variables in your programs to ensure reliability and efficiency.

Step 1: Initialization of Fundamental Datatypes
Initialization of fundamental types such as int, bool, and double is simple. Just place an assignment operator followed by a proper initializer in the declaration. For example:

int main() { int stat=0; double salary=0.0; bool temp=false; employee *p=NULL; // }

Notice that each initializer is of the correct type. This isn't really necessary since, as a special case, C++ allows you to use 0 as a universal initializer for fundamental types, including pointers, pointers to functions and even pointers to members. Therefore, you may initialize temp like this:

bool temp=0; // 0 is converted to 'false'

Likewise, you may initialize all pointer types like this:

employee *p=0; //converted to NULL void (*pfunc)(int)=0; //pointer to function void (A::*pfunc)(int)=0; //pointer to member function

In fact, you are advised to use plain 0 instead of NULL in pointer initializations. This will save you the trouble of #including a special header.

Comment and Contribute








