Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Take Charge and Initialize Your Own Data : Page 2

C++ doesn't initialize automatic variables for you, and if you're unfamiliar with the right syntax or aggregate initialization, you can misuse important library functionsor you might be tempted to skip initialization altogether. Avoid creating unnecessary performance overhead, future maintenance problems, and potential bugs by learning how to correctly initialize data on your own.


advertisement
Step 2: Array Initialization
Syntactically, initializations look like ordinary assignments. However, there are substantial differences between the two. Conceptually, an initialization takes place at compile time whereas an assignment takes place at runtime. More importantly, you are allowed to initialize an array or a an aggregate (I will discuss aggregates shortly) but you cant assign to them:

char name1[5]="John"; //OK, initialization char name2[5]; name2= "John"; //compilation error: assignment to an array

When initializing an array, you are allowed to use fewer initializers than the number of its elements (the opposite, however, is forbidden). It is guaranteed that the remaining elements are default-initialized in this case. For example, in the following expression, the array num has five elements but only the first three have explicit initializers:

int num[5]={0,1,2};

The elements num[4] and num[5] are automatically initialized to 0 in this case. Thus, to zero-initialize a large array you can provide a single initializer and let the compiler take care of the rest:


double results[500]={0.0}; //the remaining 499 elements // are initialized to 0.0 as well

This form has the same effect:

double results[500]={0};

Or, if you're using a char array:

char URL[2048]={0}; //all elements are initialized to '\0'

Notice how cumbersome and error prone a memset() call looks in comparison:

#include <cstring> char URL[2048]; memset(URL, 0, 2048);

Not only do you need to #include a special header, this form also presents a serious maintenance problem if the size of the array changes in the future. Worse yet, programmers tend to confuse between the second and third arguments:

int arr[100]; memset (arr, 100*sizeof(int), 0); //oops, meant (arr, 0, 100*sizeof(int))

This code compiles and links fine but at runtime the array elements will contain garbage values.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap