RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Tackling the Conundrums of Constant Expressions-3 : Page 3

Compile-time Evaluation
In time critical applications, constants are often chosen for performance reasons i.e., to ensure compile time evaluation of expressions. MIN can be evaluated at compile-time if C::getval() is inlined (every decent compiler will inline the call anyway). Thus, performance-wise, MIN and MAX are equally efficient. However, MIN isn't an integral constant expression even when C::getval() is inlined since the rules of constant integral expressions are very strict. To qualify as a constant expression, MIN's initializer must be one of the following:
  • A literal such as 5, 8ul, 'z', and false
  • An enumerator
  • A sizeof expression
  • A const static data member initialized with a constant expression
To turn MIN into a constant expression, it's therefore necessary to replace the C::getval() call with a literal. If you're concerned about the maintenance problems that hard-coded literals might incur, use a macro instead. Yes, in spite of the fair criticism that macros often attract, they are still useful in some cases, so to speak:

#ifndef C_GETVAL
#define C_GETVAL 4

const int MIN=C_GETVAL;
Lo and behold, MIN is now a valid constant expression:

enum SIZES 
 S=MIN, //now OK
 XL=MAX //fine

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date