Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'initialization' exactly mean?

Tags:

c++

c

linker

My csapp book says that if global and static variables are initialized, than they are contained in .data section in ELF relocatable object file.

So my question is that if some foo.c code contains

int a;
int main()
{
    a = 3;
}`

and example.c contains,

int b = 3;
int main()
{
...
}

is it only b that considered to be initialized? In other words, does initialization mean declaration and definition in same line?

like image 382
Jinwoo Park Avatar asked Dec 10 '25 12:12

Jinwoo Park


2 Answers

It means exactly what it says. Initialized static storage duration objects will have their init values set before the main function is called. Not initialized will be zeroed. The second part of the statement is actually implementation dependant, and implementation has the full freedom of the way it will be archived.

When you declare the variable without the keyword extern you always define it as well

like image 159
0___________ Avatar answered Dec 12 '25 02:12

0___________


Both are considered initialized

They get zero initialized or constant initalized (in short: if the right hand side is a compile time constant expression).

If permitted, Constant initialization takes place first (see Constant initialization for the list of those situations). In practice, constant initialization is usually performed at compile time, and pre-calculated object representations are stored as part of the program image. If the compiler doesn't do that, it still has to guarantee that this initialization happens before any dynamic initialization.

For all other non-local static and thread-local variables, Zero initialization takes place. In practice, variables that are going to be zero-initialized are placed in the .bss segment of the program image, which occupies no space on disk, and is zeroed out by the OS when loading the program.

To sum up, if the implementation cannot constant initialize it, then it must first zero initialize and then initialize it before any dynamic initialization happends.

like image 35
darune Avatar answered Dec 12 '25 02:12

darune



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!