xyz
xyz

Reputation: 8917

Initialization of auto and global variabes in C

If I understand right that global variables (which go into data segment) in C are initialized where auto variables (which go into stack) are not. or perhaps the other way round?

Why is it so? What is merit of compiler not initializing both kind of variables? Does it increase speed etc?

Upvotes: 3

Views: 1004

Answers (2)

Peter Alexander
Peter Alexander

Reputation: 54270

As you say, global variables go in the data segment, so their value is contained in the final executable, and it might as well be an initialised value as there is no performance difference either way.

On the other hand, local variables are allocated onto the stack, which is set up at run time, so initialising them would have a performance hit.

Upvotes: 4

littleadv
littleadv

Reputation: 20272

You understand right, global are initialized, auto are not. This is because globals are loaded directly from the program binary image and the initialization is "free", whereas auto are on stack, and code needs to run to change values and initialize them (i.e.: performance hit).

Upvotes: 1

Related Questions