Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tackling the Conundrums of Constant Expressions-3 : Page 3


advertisement
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 #endif const int MIN=C_GETVAL;

Lo and behold, MIN is now a valid constant expression:

enum SIZES { S=MIN, //now OK L=512, XL=MAX //fine };





Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap