Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

#include<stdio.h>
int initializer(void)
{
    return 50;
}
 
int main()
{
    static int i = initializer();
    printf(" value of i = %d", i);
    getchar();
    return 0;
}

This code will not compile in C because static variables need to be initialised before main() starts. That is fine. But this code will compile just fine in a C++ compiler.

My question is why it compiles in a C++ compiler when static has the same usage in both languages. Of course compilers will be different for these languages but I am not able to pin point the exact reason. If it is specified in the standard, I would love to know that.

I searched for this question on SO , found these similar questions:

  • Difference between static in C and static in C++??
  • Static variables initialisation order
  • Static variables in C and C++
like image 839
Anon Avatar asked May 07 '11 15:05

Anon


2 Answers

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.

like image 89
Johannes Schaub - litb Avatar answered Oct 21 '22 18:10

Johannes Schaub - litb


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++.

like image 45
Prasoon Saurav Avatar answered Oct 21 '22 18:10

Prasoon Saurav