One could write a big article on the difference between the two styles one can encounter, people who initialize variables always when declaring them and people who initialize them when necessary. I share a big project with someone who is in the first category and I am now definitly more of the second type.
Always initializing variables has brought more subtle bugs and problems than not and I will try to explain why, remembering the cases I found.
First example:
struct NODE Pop(STACK * Stack)
{
struct NODE node = EMPTY_STACK;
if(Stack && Stack->stackPointer)
node = Stack->node[--Stack->stackPointer];
return node;
}
This was the code written by the other guy. This function is the hottest function in our application (you imagine a text index on 500 000 000 sentences in a ternary tree, the FIFO stack is used to handle the recursion as we do not want to use recursive function calls).
This was typical of his programming style because of his systematic initialization of variables. The problem with that code was the hidden memcpy
of the initialization and the two other copies of the structures (which btw were not calls to memcpy
gcc's strange sometimes), so we had 3 copies + a hidden function call in the hottest function of the project.
Rewriting it to
struct NODE Pop(STACK * Stack)
{
if(Stack && Stack->stackPointer)
return Stack->node[--Stack->stackPointer];
return EMPTY_STACK;
}
Only one copy (and supplemental benefit on SPARC where it runs, the function is a leaf function thanks to the avoided call to memcpy
and does not need to build a new register window). So the function was 4 times faster.
Another problem I found ounce but do not remember where exactly (so no code example, sorry). A variable that was initialized when declared but it was used in a loop, with switch
in a finite state automaton. The problem the initialization value was not one of the states of the automaton and in some extremly rare cases the automaton didn't work correctly. By removing the initializer, the warning the compiler emitted made it obvious that the variable could be used before it was properly initialized. Fixing the automaton was easy then.
Morality: defensively initialising a variable may suppress a very usefull warning of the compiler.
Conclusion: Initialise your variables wisely. Doing it systematicaly is nothing more than following a cargo-cult (my buddy at work is the worse cargo-culter one can imagine, he never uses goto, always initialize a variable, use a lot of static declarations (it's faster ye know (it's in fact even really slow on SPARC 64bit), makes all functions inline
even if they have 500 lines (using __attribute__((always_inline))
when the compiler does not want)