Madhav said:
Hi all,
I did not understand why do the global vars are
initialized to NULL where as the block level variables have random
values? I know that the C standard requires this as was mentioned in a
recent thread.
The Standard requires that all static and file scope objects that are not
explicitly initialised by the program are given default static initialiser
values, viz. 0, 0.0, NULL (recursively for aggregates).
The Standard makes no such demands for automatic objects, except in the case
of partial initialisation of aggregate objects (where the partial
initialisation is honoured, and the rest of the object initialised as
mentioned earlier).
I want to know why this descrimination is in place.
I don't know why statics and file scope objects get a default
initialisation. I know why automatics don't. It's a programmer choice. If
the programmer wishes the program to spend time assigning 0-values to
automatic objects, the programmer can choose that behaviour by writing:
int i = 0;
and if he doesn't wish that, he can simply write:
int i;
which indicates that, at this stage, he isn't fussed about i's value.
Can't all the
variables be initialised to NULL automatically by the compiler?
Yes, a compiler is free to do that if it wishes (NULL for pointers, 0 for
integers, 0.0 for floating point numbers, and the obvious for structs,
unions, and arrays), but it is not /required/ to do that.
This would make programming a little easier.
I'm tempted to agree, but it would diminish programmer choice. I like my
objects to start off with known values, in the interests of determinism, so
your proposal would suit my style of programming. But other programmers
prefer it the way it is now, and whilst it is possible for me to get the
effect I want by taking the current strategy and adding code (typically as
simple as = {0} in my case), the reverse would not be true.
I am not (yet) so monumentally egomaniacal as to insist that every C
compiler writer in the world should change their product just to suit my
coding style. But I'm working on it.