Difference between initialization of static variables in C and C++

后端 未结 3 1518
鱼传尺愫
鱼传尺愫 2020-12-11 00:26

I was going through the code at http://geeksforgeeks.org/?p=10302

#include
int initializer(void)
{
    return 50;
}

int main()
{
    static i         


        
相关标签:
3条回答
  • 2020-12-11 01:04

    Static variables in C need to be initialised with a value known at compile time. This requirement has been removed in C++, and you can initialise them with expressions evaluated at run-time.

    The two languages differ in this, and many, many other respects. You can quite easily write C code which will be acceptable to a C++ compiler, but the reverse is not true.

    0 讨论(0)
  • 2020-12-11 01:09

    It compiles in C++ because C++ needs to support dynamic initialization anyway, or you couldn't have local static or non-local objects with non-trivial constructors.

    So since C++ has this complexity anyway, supporting that initialization like you show isn't complicated to add anymore.

    In C that would be a big matter because C doesn't have any other reason to support initialization done at program startup (apart from trivial zero initialization). In C, initial values of file-scope or local static objects can always statically be put into the executable image.

    0 讨论(0)
  • 2020-12-11 01:09

    6.7.8/4 [C99]

    All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

    In static int i = initializer(); the RHS is not a constant expression and so the code doesn't compile in C.

    In C++ there is no such restriction and the code is well-formed in C++.

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