Initializing a static variable by calling a function gives a compilation error?

#include <stdio.h> int foo(){ return 1; } int main(void) { static int q = foo(); return 0; } 

Here is a link to the same. This is C code, not C ++. It compiles and works fine in C ++, but not in C.

This code received a compilation error. Can someone explain why this is a mistake? Can static members be initialized with constant values? In C ++, we need to DEFINE static members after they are declared, why is this not required in C? I could not find a thread with a similar query or a good answer.

+7
source share
3 answers

Global and static variables can only be initialized with constant expressions known at compile time. A call to foo() does not mean using a constant expression. In addition, the order in which global and static variables are initialized is not specified. Typically, calling foo() means that there must be a certain order, because the function can reasonably expect some other variables to be initialized.

IOW, in C, none of your codes are executed before main() .

In C ++, there are ways around it, but not in C.

+6
source

All static variables are compile time, and the function gives a result at runtime, so you initialize the compile time variable with a run-time variable that is not possible, therefore it gives an error.

Another example might be the following:

 int main() { int p=9; static int x=p; } 

The above code also gives you a compile time error. The reason is the same as above.

+4
source

If you do this in C rather than C ++, you can assign the values โ€‹โ€‹of the static variables available at compile time. Therefore, the use of foo () is unacceptable because its value is not determined until runtime.

+1
source

All Articles