Does Declaring a Global Variable in C Alter the Entry Point?

Take this example.

#include "stdio.h"

int global_var=5;

int main ()
{
    int local_var=6;
    //some statements

    return 0; 
}

If the main function is the only entry point, then when does the declaration and assignment of global_var happen?

On a related note, is the global_var allocated in the heap or the stack? Also, is there a way to declare a global variable from a function, while respecting the entry point?


Conceptually, the initialisation of global variables happens before main is entered. Here I'm assuming that all your code was compiled in one translation unit: more formally a global variable is initialised immediately before any function defined within the translation unit defining that global variable is encountered. (Although a compiler can optimise this if there are no side effects).

Neither C nor C++ mention the heap or stack in their standards: they are implementation concepts, not language concepts.

So global_var could be allocated on a heap, but it might be on some kind of stack that is set up before main is entered.

There's no way of declaring a global variable within a function. A static variable within a function can mimic much of the behaviour of a global varaible but conceptually, the static is initialised the first time the function is encountered.


Initialization of global variable happen before it entered into the main .

No you cannot declare global variable inside any function. If you declare any variable inside the function then scope of that variable will be limited to that function only. Instead of global variable you may try achieving your goal by using static variable.

Global variables are stored neither in stack nor in heap. Every program (executable code) is typically divided into four sections.

Code
Data
Stack
Heap

Global variables along with constants/literals are stored in the Data section. Source : Where does variables stored in memory?

PS : static variable can be initialized only once.

链接地址: http://www.djcxy.com/p/82500.html

上一篇: 缓冲区溢出不影响const变量?

下一篇: 在C中声明全局变量是否改变了入口点?