[LC++]enum, #define, const, static const, or member const???
Carlo Wood
carlo at alinoe.com
Mon Apr 8 22:36:06 UTC 2002
On Mon, Apr 08, 2002 at 05:59:07PM +0930, Mark Phillips wrote:
> Why is this bad? If all the data handling routines use the
> enums appropriately, the data will all shift perfectly without
> error.
Because it is less maintainable. How do you know that another
programmer who added code 5 months ago in the 4 megabyte big
source subtree artificial-intelligence/ didn't use your enum
in a slighty different way? You'd have to check the correct
usage in ALL of the 150 megabytes source code...
The point that I am trying to make is that you shouldn't
use enums when you need to assign values to them in a way
that insertion of new values at any point doesn't work anymore.
Your examples worked and were correct, but you used the edges
of the subgroups. This would break:
enum foo {
green = 0,
yellow = 1,
blue = 2,
white = 3
};
// USE the integer values:
if (color == 2) // we know it is blue
...
if (color1 - color2 == 1) // Hey, that seemed the best way to detect that color1 == green && color2 == blue
...
array[yellow].ugly_color();
'save array to disk'
...
char colorNames[] = { "green", "yellow", "blue", "white" };
...
if (color & 1) { 'a light color' } // Overloading the least-significant bit
Because each of these uses would break when you insert a new value and change
the values of the enums.
You could do this however:
enum Color {
// Light Colors
start_light_colors,
yellow,
white,
end_light_colors,
// Dark colors
start_dark_colors,
blue,
green,
end_dark_colors
};
> > no. If your compiler does that then it is non conforming to ISO C++.
> >
> > int const x = 3; // Exported.
> > static int const y = 4; // Not exported.
>
> Does that mean x will have an address by default?
Yes, pointing to the read-only section.
> I thought that
> unless the address of x is asked for, it will inline the value 3.
It will, x is constant.
> If I'm right then "int const" will behave the same as "static
> int const" except in the case of the address of x being referred
> to. Is this right?
Hmm, yes - you seem to be right. I guess I never left away
the 'static' unless I also add an 'extern', in that case
it is exported. Nevertheless I remember a case where I added
non-static constants to a header file and that gave linker
errors :/ (multiple inclusions).
--
Carlo Wood <carlo at alinoe.com>
More information about the tuxCPProgramming
mailing list