0

In the below example, I get an error on compilation

int main() {

    int x = 10; // guess this is runtime initialisation
    static int y = x; //guess this is loadtime initialisation

    printf("x = %d, y = %d", x, y);

}

Error:

    error: initializer element is not constant

My understanding is this is related to the way static and global members are initialised as against auto variables. I wanted to know the difference between the load time , runtime and compile-time initialisation I also wanted to know about the element's value getting stored in data section and stack and its effect on initialisation.

Aadishri
  • 1,341
  • 2
  • 18
  • 26
  • I think load-time and compile-time are the same. At least from the point of view that both occur before run time. – Alexey Frunze Apr 17 '13 at 11:51
  • 1
    You should really look your questions up before asking because they may have been already asked and answered. Type in the relevant keywords (`[c]`, `static`, `initialize` here), use google too. – Alexey Frunze Apr 17 '13 at 11:58

3 Answers3

0

I'd say in C there is no difference between compile-time and load-time. The same is not true of C++: POD constants are initialized at compile time, while global/static objects with constructors are initialized at load time.

In your example, you try to initialize a compile-time value with a run-time variable's contents, so it fails. In C++, if x were declared const, it would be recognized as a compile-time constant and succeed.

Medinoc
  • 6,577
  • 20
  • 42
0

Static variables came to life before the automatic variable or say local variable so u can't use any variables for initialization of static variable u can only use constants for initialization of static variable.

Load time initialization and compile time initialization is same in C and runtime initialization is may be not supported in C ..it is supported in C++ but i don't know about C

umang2203
  • 78
  • 5
  • Runtime initialization is definitely supported in C. That `x` in `main()` does not even exist outside of run time, so it's created and initialized at run time. – Alexey Frunze Apr 17 '13 at 12:17
0

constants are initialized at compile time, while global/static variables are initialized at load time so you cannot initialise global/static variable with load time with run time stack variables if we can convert x to const(c++) it would run ok.

anshul garg
  • 473
  • 3
  • 7