Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically initializing a static value in C vs C++ [duplicate]

Tags:

c++

c

#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 Answers

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

like image 50
Lior Avatar answered Mar 11 '26 07:03

Lior



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!