C Language

Your Constant Companion

Another one of C++'s "pluses" helps here. In most cases, you can-and should-use const variables instead of macros to define mnemonics for constant values. In the example above, if you use

 const int MAX_FILES = 10; // Limit to open files

instead of the #define, the comment poses no problem. Another advantage of const variables over macros is that the compiler parses the variable name and places it in the program's symbol table, which allows the variable to be type-checked when referenced and to be used by cross-reference and debugger tools. Also, like other variables, const variables can have restricted visibility, thus avoiding name clashes between different sections of code.

One place where you have to use a C++ "trick" instead of const is when you want to declare a constant within the scope of a class. The following syntax is illegal because you can't assign an initial value to a static class member:

 class file_list {
    static const int MAX_FILES = 10; // Illegal!
    char * file_name[ MAX_FILES ];
 };

A workaround can be used for integer constants by defining an enumeration containing the symbol and its value:

 class file_list {
    enum { MAX_FILES = 10 }; // Legal
    char * file_name[ MAX_FILES ];
 };

As the above example shows, C++ has some helpful refinements over C, but maintains the C tradition of complex usage rules. If you aren't convinced that C++ adds complexity, as well as capability, consider the rest of the story on static class members. Because a C++ class is a type, not a data object, and only one copy of a static class member exists (unlike non-static class members, which have one instance per object of the class), you have to define and initialize static members outside the class definition.

 class classX {
    static int objX_cnt; // Can't initialize here!
 };
 ...
 int classX::objX_cnt = 0; // Initialize here.

And you can't use static in the objX_cnt variable definition because that would conflict with the use of static for global (not member) objects. If these rules seem burdensome, prepare yourself for the full force of C++, because this is just the beginning.

by BrainBellupdated
Advertisement: