int a = 5;
int b = a; //error, a is not a constant expression
int main(void)
{
static int c = a; //error, a is not a constant expression
int d = a; //okay, a don't have to be a constant expression
return 0;
}
I don't understand what happens when a C compiler handles those variable declarations.
Why was C designed to be unable to handle
int b = a?
The specific rule that applies here is C 2018 6.7.9 4:
The primary reason for this arises from the way that C is typically implemented, with a compiler generating object modules (which are later linked into executables and run). In such a C implementation, initializing an object with static storage duration requires the compiler to know the initial value, whereas initializing an object with automatic storage duration does not require the compiler to know the initial value.
This is because, to initialize an object with static storage duration, the compiler must put the initial value into the object module being generated. To initialize an object with automatic storage duration, the compiler merely needs to generate instructions to get or calculate the initial value and store it in the object.
When
int a = 5;andint b = a;appear outside of any function,aandbhave static storage duration. At this point, the compiler could, in theory, see thatawas initialized with the value five, so it has that value when used inint b = a;. However, there are some issues with this:buses only objects that have been initialized earlier in the same translation unit. Extending the language to require the compiler to support this would require more complicated rules.Another possibility would be that, to make initializations like
int b = a;work, the compiler does it by generating instructions to be executed when the program starts, possibly immediately beforemainis called. This adds complications, including:int b = a;appears in a translation unit other than the one containingmain, how is the code necessary to initializebinserted inmainor in the program start-up code?These problems could be solved, in theory, but C is intended to be a “simple” language.