I had declared a Boolean variable bool abc;
in a class and thought that it would be false by default. An if condition in my program, if (abc)
,
Yes. Always initialize your variables before use. Even if the language guarantees that they will have specific values. If you can't force yourself, get a compiler that will complain, and then make yourself do that. :)
However, don't initialize values unless it really has a meaning for them to be initialized. For example, if you have a loop like this (I'm not saying this is good code, it's just an example):
int i = 0;
while ((i = getNum()) == 5)
{
}
Don't initialize i
to zero like I did. It makes no sense, and while it shuts up the compiler, it introduces the possibility that you'll forget it and then your code will be messed up. If you can force yourself to initialize only at the right times -- no more, no less -- then you'll make debugging a heck of a lot easier, since your wrong code will look wrong even at just a glance.
So, in one line: Never initialize just to prevent the compiler from complaining, but always initialize before use.