Sunday, 1 May 2016

Why C/C++ standard not recommending to initialize the variable to zero when declaring a variable?

int a;
printf(“%d”,a); // We will get garbage value

This is because memory for the auto variables is allocated at runtime. Assigning the variables with zero when declaring a variable may incur a runtime cost. Consider the following statement with huge array size

Variable initialization:

//initialize array
int a[2000];
initialize_array(a); // calling function and assign “-1” 

Here the actual programmers intention is to initialize the array a with “-1”. If compiler assigns zero in the first line while creating the variable then application will waste the time in assigning the array with zero because actual users intention is to assign “-1”.