Sriram Rajagopalan said:
Hi,
Which of these two would be a better way of initializing the local
variables? and why?
1) At the time of their declaration.
2) Just before their use.
Well, you now know from reading the other responses that 1) is stupid and 2)
is stupid. You've been shown a 3) which is, naturally, stupid. And yet it's
hard to imagine a 4), isn't it?
So you have to make a judgement call.
Let's wrap up (3) into (1), since they are basically the same - i.e. "give
it the best you've got, at definition time". So:
Method 1 - initialise all auto objects to some default value unless their
proper starting value is actually known at definition time. This has the
advantage that, in the event of your (incorrectly) using a value before its
proper starting value has been calculated, the behaviour of the program is
deterministic and therefore easier to debug.
Method 2 - leave auto objects in an indeterminate state until their proper
starting value is known. This has the advantage, on some implementations,
that incorrectly using an indeterminate value may, if you are fortunate,
lead to the program "crashing", "segfaulting", "coredumping",
"access-violating", or call it what you will, leading to early detection -
but this is far from guaranteed. It has the further potential advantage of
being microscopically faster. Furthermore, *some* (but not all) compilers
can detect *some* (but not all) usages of indeterminate values, giving a
touch of reassurance which may or may not comfort you.
Which you choose is up to you. Personally, I favour Method 1, but I
recognise that there are some genuinely expert programmers in this
newsgroup who prefer Method 2. I respect their choice, and they respect
mine. Both approaches are valid, and to some extent your choice will depend
on other aspects of your programming style (for example, whether your
functions are typically short or long!).
Like I said, it's a judgement call. It is not as clear-cut as some of the
other responses have suggested.