#include <stdio.h>
int foo(){
return 1;
}
int main(void) {
static int q = foo();
return 0;
}
Here is a link for the same. This is a C code and not C++. It compiles and run fine in C++ but not C.
This code was getting compilation error. Can someone please explain why is it getting error? Can static members only be initialized by constant values ? In C++ we need to DEFINE static members after declaring them , why is it not required in C ? I couldn’t find any thread with similar query or a good answer.
Global and static variables can only be initialized with constant expressions known at compile time. Calling your
foo()function does not constitute using a constant expression. Further, the order in which global and static variables are initialized is not specified. Generally, callingfoo()would mean that there must be a certain order, because the function can reasonably expect some other variables to be already initialized.IOW, in C, neither of your code is executed before
main().In C++ there are ways around it, but not in C.