3
#include <stdio.h>

int b(){
 return 5;
}

int main(){
 static int a = b();
 return 0;
}

Above code doesn't compile in C with this error:

error: initializer element is not a compile-time constant

but compiles fine in C++. What are the differences between initializing static values in C and C++?

1 Answers1

1

From cppreference:

Variables declared at block scope with the specifier static or thread_local (since C++11) have static or thread (since C++11) storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered). On all further calls, the declaration is skipped.

So, in C static is initialized at startup, while in C++ during the first time the code passes through this section of code. This will allow assignment of a return from a function in C++ which would be impossible in C since C would need to know the value before the program starts to run...

I hope this helps Lior

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
Lior
  • 284
  • 1
  • 6