The compiler doesn't really put all the memory for objects in uninitialized global variable data space, only enough of the memory so tht the linker can resolve all addresses. The memory for them is allocated then the program is loaded into RAM. The compiler can't do that if you initialize the variable like in your second code snippet.
BTY: Uninitialized global variables are initialized to be all 0s when the program is loaded into memory (this is part of your program's startup code that the compiler adds before calling function main). So the code in your second code snippet has no value.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
@ Ancient Dragon, if both are same,why is there a difference in code size in both cases. The initialization of global variables happens before the main() takes off, loosly at the startup. Isn't it?
Please read Ancient Dragon's post for the answer.
gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
In Turbo C, I observed that the code size for initialized or uninitialized variables is the same.
Some compilers are smarter than others :) Turbo C is not a very smart compiler.
>>if both are same,why is there a difference in code size in both cases
What I meant by that is int x; and int x = 0; when declared on global memory are the same, in both versions the compiler initializes the variable to 0.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387