Saturday, October 25, 2008

const or not const

 From the C++ FAQ:
const identifiers are often better than #define because:
  • they obey the language's scoping rules
  • you can see them in the debugger
  • you can take their address if you need to
  • you can pass them by const-reference if you need to
  • they don't create new "keywords" in your program.
[...] There are cases where #define is needed, but you should generally avoid it when you have the choice.
Nice said, and everybody believes it. Until you realize that these "const identifiers" really are "const variables", which is an oxymoron.

"Distinction without difference.", you think? Well, then look at this example:

const double FACTOR = 0.75;
const unsigned HEIGHT = unsigned(FACTOR * 5);
unsigned char a[HEIGHT];

which let's the compiler dump the following error
error: array bound is not an integer constant

Ah, yes, an unsigned const variable is no integer constant, right.... wtf?
    As far as I understood the standard the compiler does not have to calculate the value of HEIGHT at compiletime. This is allowed because const identifiers are nothing but read only variables. So this simple example already is a case where you have no other choice but use the good old C style:

#define FACTOR 0.75
#define HEIGHT unsigned(FACTOR * 5)
unsigned a[HEIGHT]; // unsigned a[unsigned(FACTOR * 5)]

This example compiles. The C++ compiler is now forced to do the calculation at compile time.  

No comments:

Post a Comment