In the following cases, C++ requires expressions that evaluate to an integral constant expression:
Contrary to popular conception, not every
const variable of an integral type is a constant expression. Consider the following two examples:
struct C
{
inline static int getval() {return 4;}
};
const int MAX=1024;
const int MIN=C::getval();
Both
MAX and
MIN are constants, eg., the program can't modify their values. However, there is a substantial difference between them.
MAX is a constant integral expression. As such, it can be used in an array declaration,
case labels, etc.:
char buff[MAX];
int sizes=getsizes();
switch (sizes)
{
case MAX:
//..
break;
default:
//..
break;
};
What about
MIN? Syntactically speaking, it's a
const object with an initializer, just as
MAX is. However, if you try to use
MIN in places where an integral constant expression is required, your compiler will complain:
struct bitpattern
{
signed nibble: MIN;//error: constant expression required
unsigned octet: 8;
};
enum SIZES
{
S=MIN, //error: constant expression required
L=512,
XL=MAX //fine
};
In the examples above, a compilation error reveals that
MIN isn't a constant expression. In fact, this is your litmus test: use a constant as an enumerator's initializer to check whether it's a valid constant expression.