S
santosh
DaveC said:I always used to initialise variables at declaration, then a couple of
colleagues started telling me it was bad practice and that the compiler
should be left to spot the use of uninitilised variables and hence
possible bugs.
Your thoughts on the above would be welcome (as an aside), but my main
problem follows.
The standard doesn't require a compiler to diagnose use of
uninitialised objects, merely that the subsequent behaviour is
undefined. So you can't rely on all compilers to catch this for you,
though almost all mainstream ones do.
Initialising variables to a safe or default value is mainly a feel-good
thing. For small functions with a few variables, which you're going to
use straightaway, dummy initialisations are not really worth it. They
may not also be worth it for functions with a large number of variables
encapsulated into structures.
If your code is correct, then dummy initialisations rarely have a
useful effect. If your code is wrong, then the default values, (often
zero), are as likely to lead to wrong results than an arbitrary value.
This is something that one should analyse on a case-by-case basis. Some
variables are really not worth initialising to safe values, while some
might benifit from them, in certain border conditions.
IMHO, initialising pointers to NULL is more relevant than initialising
non-pointer objects. An arbitrary value in a pointer will give you no
idea of whether it is pointing to valid object or not, while zero is
always indicative of an unusable pointer. The same is not often true
for scalar variables, zero may often be a valid value. Correct code is
more important than relying on dummy initialisations and compilers.