Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable 0-initialized penalty

Tags:

c++

This is a very simple question:

Does 0-initializing global and static variables have any performance penalty (albeit very small) at runtime?

like image 591
Dean Avatar asked Oct 14 '15 13:10

Dean


People also ask

Are global variables always initialized to 0?

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.

Are global structs initialized to 0?

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.

Do global variables need to be initialized?

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.

Why is it bad to declare global 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.


1 Answers

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.

like image 184
Lundin Avatar answered Oct 12 '22 14:10

Lundin