I am reading a book which mentions this
If the compiler knows every use of the const, it need not allocate
space to hold it. For example:
const int c1=1;const int c3=my_f(3);extern const int c4;Given that values of c3 and c4 are not known as compile time, storage
must be allocated for c3 and c4.
I didn’t understand any of this. My doubts are:
What does it mean by holding here? Wouldn’t it still need to store everything in memory?
For c1, wont we have any storage allocation?
Please clear my doubts.
Thank you.
c1is different from the other two constants in that it is initialized with a literal value. This lets compiler put that value everywhere the constant is used, like this:can be replaced by
This means that the compiler does not need to allocate space and store
1in it.c3andc4are different: one is calculated using a function, and the other one is supplied from a different compilation unit. This means that the compiler can no longer perform the substitution the way it could withc1: the values of thec3andc4are not known to the compiler. Therefore the compiler generates code forin the same way as if
c4were a variable stored in some place in memory. Since in this casec4is an external constant, the linker will resolve its location, and fill in the information the compiler is missing (namely, the address ofc4) to make the program complete and ready to run.