Martin Ambuhl <ma*****@earthlink.netwrites:
ko********@yahoo.com wrote:
>{
const int state_black = 1 ;
const int state_white = 2 ;
int state ;
state = state_black ;
switch(state)
{
case state_black:
break ;
case state_white:
break;
}
}
why is this not acceptable?
state_black and state_white are variables, not constants, and switch
labels must use compile-time constants.
>why can't declaring the variable const make it suitable to use with
the case label?
Because the variable is still a variable, and not a compile-time constant.
state_black and state_white are "variables", sort of, except that they
aren't allowed to vary.
I think using the term "variable" to something that can't legally be
modified may be a bit misleading. (A cast can be used to get around
the "const" qualification and attempt to modify it, but any attempt to
do so invokes undefined behavior.)
The standard uses the term "object", not "variable".
As question 11.8 in the FAQ explains, the "const" qualifier really
means "read-only", not "constant". Quoting the FAQ:
The const qualifier really means ``read-only''; an object so
qualified is a run-time object which cannot (normally) be assigned
to. The value of a const-qualified object is therefore not a
constant expression in the full sense of the term, and cannot be
used for array dimensions, case labels, and the like. (C is unlike
C++ in this regard.) When you need a true compile-time constant,
use a preprocessor #define (or perhaps an enum).
For the above, it would have made more sense to declare:
enum state { state_black = 1, state_white = 2 };
The "= 1" and "= 2" could be omitted if you don't care about the
values, as long as they're distinct.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"