Cognzant Technology Solutions Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
As far as my knowledge the default value of global variable is garbage.
I think u r right. Bt in this context I have one question that,
Uninitalized global variable stored in bss segment and the initialized global variables stored in data segment. Then if the compiler autmatically sets the value of global variable to Zero. Then what is the requiremnt of bss segment. And what is the use of "static" keyword, as it also does the same, if both have declared in the same file. Look at the below example;
int i;//Compiler sets the value to Zero.
int j = 0;// Here user sets to Zero.
static int k;//Default is Zero
main()
{
printf("%d...%d...%d",i, j, k);
}
What makes the difference in the above program?
The .bss segment is an optimization. The entire .bss segment is described by a single number, probably 4 bytes or 8 bytes, that gives its size in the running process, whereas the .data section is as big as the sum of sizes of the initialized variables. Thus, the .bss makes the executables smaller and quicker to load. Otherwise, the variables could be in the .data segment with explicit initialization to zeroes; the program would be hard-pressed to tell the difference. (In detail, the address of the objects in .bss would probably be different from the address if it was in the .data segment.)
Since i is an unsigned global variable it goes into BSS for storage and bss initializes its every variables with '0'.
hence zero output.
In BSS section stored only static variables by default initializing 0. The non-static variables don't store in BSS part! One of the differences of static and non static declarations is that static variables seen only in file where declared non static variables you can use in other files.
Default value for a global variable is 0
- Saurabh Singhal August 15, 2013