On 22/10/2013 22:36, ThosRTanner wrote:
> On Tuesday, October 8, 2013 10:38:14 PM UTC+1, James Kuyper wrote:
>> I prefer to leave variables uninitialized if I cannot initialize them
>> with the value they're supposed to have the next time their value is
>> read. That's because any decent compiler will give you a warning if its
>> analysis of the code flow suggests that there's a possibility of the
>> value of that variable being read before it gets written. Initializing a
>> variable with a value that's not actually intended to be used turns off
>> that warning, because the compiler doesn't know that you don't intend it
>> to be used.
> I have to say I prefer the other way round, and also to keep the declarations in as small a scope as possible (i.e. only in the block, rather than declaring every variable ever used at the top of the function). Given you have a decent compiler, it should be able to tell you that you have assigned a value to a variable without using it as well as reading before initialising.
In the long distant past (in computer terms where a second is a long
time) local variables had to be declared at the start of a block where
they were used. This meant that that either you had to delay
initialisation until you could provide a valid value or you had to
create ever more deeply nested blocks.
More recently the rules have been changed so that variables can be
declared, defined and initialised (largely) at the point of first use.
That means that we can almost always delay definition until we are ready
By the way, the difference between declaration and definition is NOT
whether the variable is initialised or not. Declarations introduce
names but do not create the object named. Definitions create objects and
attach a name. It is not possible (I think) to write a definition that
is not a declaration but it is possible to write declarations that are
declares foo to be the name of a function that takes no arguments and
defines a function that takes no arguments and returns nothing and binds
the result to the name foo which is also declared by that statement. If
foo has previously been declared the implementation will attempt to link
the two declarations.
extern int i;
Declares that i is the name of an int but does not create an int object
(that is simplified because C has a number of extra rules to confuse the
simple minded :)
Defines an uninitialised int (i.e. assigns storage for an int value but
does not initialise it) and then binds the name i to that storage.