Initialization of global variables

R

Rahul Gandhi

Hi,
Which one preferable with respect to code size of the executable
Un-initialised global variables
or initialised global variables


regards
Rahul
 
P

Peter Nilsson

Rahul Gandhi said:
Hi,
Which one preferable with respect to code size of the executable
Un-initialised global variables
or initialised global variables

The standards don't have anything to say on the resultant executable size of
a program for either case.

That said, either your globals _need_ initialising or they don't, so I don't
see the point of the question.

The code...

int global = 42;

....is a lot simpler and more robust than...

int global;

int main(void)
{
global = 42;
/* ... */
return 0;
}

If the global is constant, straight initialisation is even more sensible!
 
C

CBFalconer

Peter said:
The standards don't have anything to say on the resultant
executable size of a program for either case.

That said, either your globals _need_ initialising or they don't,
so I don't see the point of the question.

int global = 42;

...is a lot simpler and more robust than...

int global;
int main(void)
{
global = 42;
/* ... */
return 0;
}

In terms of source code, yes. In practice, no, for two reasons.
First, main may be called recursively in C, so the meanings are
quite different. Second, the presence of _any_ initialization for
'global' data may trigger large arrays of zeroes in the executable
on some systems. There is no standard for this, of course, but
the absence of such initialization ensures it doesn't happen.

This is a religious issue, and sure to draw fire, but I prefer to
NOT initialize and write specific initialization code where it is
needed. That way you are also not hiding the fact that local
(automatic) variable initialization generates code. It also
allows you to count on the fact of 0 initialization for static
variables.
 
D

Dan Pop

In said:
Which one preferable with respect to code size of the executable
Un-initialised global variables
or initialised global variables

Uninitialised global variables result in more compact executables on some
platforms. Consider the following two programs, that have identical
semantics:

fangorn:~ 319> cat ini.c
int array[10000] = {0};

int main() { return 0; }
fangorn:~ 320> gcc -o ini ini.c
fangorn:~ 321> cat noini.c
int array[10000];

int main() { return 0; }
fangorn:~ 322> gcc -o noini noini.c
fangorn:~ 323> ls -l *ini
-rwxr-xr-x 1 danpop sysprog 54318 2004-02-02 18:27 ini
-rwxr-xr-x 1 danpop sysprog 14328 2004-02-02 18:28 noini

Dan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,836
Latest member
BuyBlissBitesCBD

Latest Threads

Top