Saturday, March 20, 2010

const in c++ ---- storage and linkage

This is the one thing which most people are unaware of in c++. Constants do not behave like normal types, i know you must be thinking that you knew this already, they are constants.


but wait for me to finish.


1.> STORAGE POINT OF VIEW


globally declared const variables are not allocated any storage space by default, compiler makes a mere entry of it in its symbol table.


This is done for the sake of optimization, as compilers in case of const implement constant folding.


Any other global variable ( non const ) is allocated memory.


But we can force the compiler to allocate memory to a const global variable by


--> passing it to a function as an argument


--> storing its address


Its because of this, linkage for const variables are also imlemented in a different manner.


2.> LINKAGE POINT OF VIEW


const by default has internal linkage, this is due to the fact that its not allocated any memory.


Consider the expression


external int a;


This line tells the compiler that this is a mere definition and declaration for this variable is given else where. When a variable is declared it is allocated some memory, which is not the case with const variables, Hence the need of keeping the default linkage as internal.


As we have seen earlier how compiler can be forced to allocate memory to a const variable, well there is one more way


By explicitly declaring the const variable as external. Which changes its linkage and as its linkage is external now compiler allocates the memory to the variable.



Hence for making a const variable external we need to specifically declare it as


extern const int a;



Hope this make the things a bit clear.


No comments:

Post a Comment