This is a very simple question:
Does 0-initializing global and static variables have any performance penalty (albeit very small) at runtime?
Yes, all members of a are guaranteed to be initialised to 0. If an object that has static storage duration is not initialized explicitly, it is initialized implicitly as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant.
According to the ANSI C standards, the fields of a global struct are initialized to zero, if they are not explicitly initialized in the code.
In C language both the global and static variables must be initialized with constant values. This is because the values of these variables must be known before the execution starts. An error will be generated if the constant values are not provided for global and static variables.
Global variables can be altered by any part of the code, making it difficult to remember or reason about every possible use. A global variable can have no access control. It can not be limited to some parts of the program. Using global variables causes very tight coupling of code.
No, since the C++ (and C) standard says that all global/static variables that are not initialized explicitly by the programmer, must be initialized to zero. Such variables are placed in a special segment called .bss
. They are initialized to zero before main() is called.
If you initialize your global/static explicitly, but to the value 0, the compiler is smart enough to realize this and still put it in the bss
segment.
You can test this for yourself with an example like this:
#include <stdio.h>
static int uninit;
static int init_zero=0;
static int init_one=1;
int main (void)
{
printf("%p\n", &uninit);
printf("%p\n", &init_zero);
printf("%p\n", &init_one);
return 0;
}
In this example, the uninit
and init_zero
variables will end up at adjacent memory addresses (likely 4 bytes away from each other), since they are both in the .bss
segment. But the init_one
variable will end up somewhere else entirely, because it is allocated in the .data
segment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With