In article <41************ ***@yahoo.com>
CBFalconer <cb********@wor ldnet.att.net> wrote:
... In C the declaration "const int number = 4;" simply creates a
variable that is expected to be read-only (but which can be altered).
Well, more precisely, it *may* be alterable, but if you try to do so,
the effect is undefined. In any case, it is indeed still a variable,
even if it never varies.
The way to get a constant usable where constant expressions are
needed (such as the size of an array) is with a #define.
This is the most general method, and the one most C programmers use.
For the specific case of "int"-valued constants, you can (mis)use
enum:
enum { number = 4 };
makes "number" an integer constant, of type "int" and value 4. This
can be used in those places that require constants, such as in
sizing arrays -- even those outside a function, or any in C89 --
or in "case" labels:
switch (func()) {
case 1:
... code for "case 1" ...
break;
case number:
... code for "case 4" ...
break;
default:
... code for other cases ...
break;
}
A "const int" is not suitable for any of those three:
% cat t.c
const int number = 4;
char foo[number];
% cc -std=c89 -pedantic -Wall -W -O -c t.c
t.c:2: warning: ISO C89 forbids variable-size array `foo'
t.c:2: variable-size type declared outside of any function
% cc -std=c99 -pedantic -Wall -W -O -c t.c
t.c:2: variable-size type declared outside of any function
% cat t2.c
enum { number = 4 };
char foo[number];
% cc -std=c89 -pedantic -Wall -W -O -c t2.c
% cc -std=c99 -pedantic -Wall -W -O -c t2.c
The "enum" method works; the "const" method does not. (I prefer
the "#define" over the "enum" myself, and "enum" does not allow
defining floating-point constants, or constants of unsigned, long,
or -- in C99 -- long long types.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it
http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.