const in C++

In C++, a const must always have an initialization value( except when you make an explicit declaration using  extern:
    extern const int bufsize;
).

A const in C++ defaults to internal linkage; that is, it is visible only within the file where it is defined and cannot be seen at link time by other translation units. Even a const defined outside all functions has file scope.



Normally, the C++ compiler avoids creating storage for a const, but instead holds the definition in its symbol table.

The C++ compiler will create storage for a const in the following situations:

1. A const is defined as extern.
   extern const int x = 1; // storage is created

2. When taking the address of a const:
   const int j = 10;
   long address =  (long)&j; // storage is created

3. It's possible to use const for aggregates, but you're virtually assured that the compiler will not be sophisticated enough to keep an aggregate in its symbol table, so storage will be allocated.
   const int a[] = { 1, 2, 3, 4}; // storage is created
   // float f[a[2]]; // illegal
The compiler allocates the storage for the array a, but it doesn't know what's inside that storage.

4. The initialization expression is too complicated or the expression is not a compile-time const value.
   const char c = cin.get(); // storage is created.

No comments: