Does it makes sense to always initialize variables to some meaningless value like zero?
I have a co-worker that religiously initialize all variables to zero even in cases that zero would cause a problem, like this:
/* assume all arrays came with same length, not null and size > 2 */
void gradient ( float * result, const float * y, const float * t, const size_t size )
{
float num = 0.0f;
/* initialization of denominator to zero doesn't make any sense to me */
float den = 0.0f;
for ( size_t i = 0; i < (size-1); i++ )
{
num = y [ i + 1 ] - y [ i ];
den = t [ i + 1 ] - t [ i ];
result [ i ] = num / den ;
}
num = y [ size - 1 ] - y [ size - 2 ];
den = t [ size - 1 ] - t [ size - 2 ];
result [ size-1 ] = num / den;
}
In the exemplified case, I proposed to at least initialize den
to some MAX_FLOAT
value. Am I wrong? Why some people believe this?
In the case where initialization is not needed, it often hints that the declaration is too early (Although not always).
In this case I would always initialize, yet defer the declaration until needed.
/* assume all arrays came with same length, not null and size > 2 */
void gradient ( float * result, const float * y, const float * t, const size_t size ) {
for ( size_t i = 0; i < (size-1); i++ ) {
float num = y [ i + 1 ] - y [ i ];
float den = t [ i + 1 ] - t [ i ];
result [ i ] = num / den ;
}
float num = y [ size - 1 ] - y [ size - 2 ];
float den = t [ size - 1 ] - t [ size - 2 ];
result [ size-1 ] = num / den;
}
In case where I need the the index after a for()
loop, I like the for
loop to do the first assignment with no prior initialization.
I like the regular syntax of int i; for (i=0; i<n; i++)
vs. int i = 0; for ( ; i<n; i++)
.
int i;
for (i=0; i<n; i++} {
...
if (...) break
...
}
// Do something with `i`
In cases where an object lacks a needed initialization, good compilers warn about such. Always initialization and with a foolish value can hide bugs. @tstanisl @Eric Postpischil
It is that past (and current weak) compilers contributed to this "always initialize" goal, hence why some people believe this today. It is less relevant today.
In other cases, code for what is most clear and set aside the always rule about unneeded initialization.