Motivated by answers to this post. Why is this NaN
I have the following code:
int main()
{
const int weeks = 10;
const int salespersons = 9;
const int days = 30;
double weekly_sales[weeks][salespersons][days];
double total_weekly_sales[weeks];
double total_overall_weekly_sales[salespersons];
int a;
cout << "a = " << a <<endl;
cout << total_weekly_sales[0] <<endl;
for(int w=0; w < weeks;w++)
{
for(int d =0; d < days; d++)
{
for(int s=0; s < salespersons; s++)
{
total_weekly_sales[w]+=weekly_sales[w][s][d];
total_overall_weekly_sales[s]+= weekly_sales[w][s][d];
}
}
}
cout << total_weekly_sales[0] <<endl;
}
It will output the following:
a = 0
0
0
Under gcc 4.5.3, with compiling option -Wall
.
I also compiled the code under here: http://liveworkspace.org/code/94SOj$2. Same output as above.
I also compiled the code under VS2010. VS2010 gaves warning as follows:
warning C4700: uninitialized local variable 'a' used
warning C4700: uninitialized local variable 'total_weekly_sales' used
When I ran:
Run-Time Check Failure #3 - The variable 'a' is being used without being initialized.
I know that it is bad practice to NOT initialize local variable and use them. I also understand it will be problematic.
My question is:
In C++ standard: is there any place saying that using uninitialized local variable will result in undefined behavior? Why does it behave differently under different compilers? Does this mean the standard actually does not enforce that all compilers should implement proper actions regarding using uninitialized local variable
? How would you tell it is undefined behavior from compiler output then?
Thanks.