Saturday 12 November 2011

Uninitialized Variables in C programming

Uninitialized Variables

Compile-time checking can also be helpful in finding uninitialized variables. Consider the following
function:

void average( float ar[] , int size )
{
float total;
int a;
for( a = 0 ; a < size ; ++ a )
{
total += ar[ a ];
}
printf( “ %f\n” , total / (float) size );
}

The problem here is that the variable total is never initialized; it therefore can, and probably will, contain
some random garbage value. The sum of all the values in the array is added to this random garbage value (this
part of the program is correct), and the average, plus the random garbage, is printed.

No comments:

Post a Comment