initializing static variable with a function call gives compilation error?

后端 未结 3 717
醉话见心
醉话见心 2020-12-19 04:52
#include 
int foo(){
    return 1;
}
int main(void) {
    static int q = foo(); 
    return 0;
}

Here is a link for the same. This i

相关标签:
3条回答
  • 2020-12-19 05:16

    All the static variables are compile time and the function is giving the output at run time so you are initializing a compile time variable with a run time variable which is not possible so it is giving error.

    Another example may be as follows

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

    the above code is also gives you compile time error,The cause is same as above.

    0 讨论(0)
  • 2020-12-19 05:25

    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, calling foo() 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.

    0 讨论(0)
  • 2020-12-19 05:26

    If you are doing this in C rather than C++ you can only assign static variables values that are available during compilation. So the use of foo() is not permitted due to its value not being determined until runtime.

    0 讨论(0)
提交回复
热议问题