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

3
  • Is this a theoretical question? Commented Feb 16, 2020 at 6:09
  • This is closely related to (but slightly different from) a previous question, Zero, static and dynamic initialization of variables in C, by the same OP. Commented Feb 16, 2020 at 6:38
  • It's in the error message. The initializer must be a constant expression in C Commented Feb 16, 2020 at 6:43

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments