20.3.1.1.  Globals and const

[ fromfile: globals.xml id: constglobals ]

The scope of const global variables is slightly different from the scope of regular globals.

A global object that has been declared const has file scope, by default. Unlike static objects declared outside of all blocks, it is possible to export a global const to other files by declaring it extern at the point where it is initialized. For example, in one file, you could have the code in Example 20.8.

Example 20.8. src/const/globals/chunk1.cpp

const int NN = 10;      // file scope
const int MM = 44;      // file scope
extern const int QQ = 7; // can be accessed from other files   

int main() {
// NN = 12;        // error
   int array[NN];  // okay
// QQ++;           // error
   double darray[QQ];
   return 0;
}


In another file, you might have the code in Example 20.9

Example 20.9. src/const/globals/chunk2.cpp

extern const int NN = 22;     // a different constant
extern const int MM;          // error
// declare global constant - storage allocated elsewhere
extern const int QQ;    // external declaration 
void newFunction() {
   int x = QQ + NN;
}



Example 20.9 has a const int NN that is separate and distinct from the const with the same name in Example 20.8. Example 20.9 can share the use of the const int QQ because of the extern modifier. Example 20.9 cannot access the file scope const MM by declaring MM with the extern modifier.