[Tfug] Developer question

Bexley Hall bexley401 at yahoo.com
Mon Jul 2 17:14:19 MST 2007


A puzzle for lurking developers... :>

I have a set of manifest constants that are used,
among other things, as indices into different 
tables.  

However, to improve the quality of the code,
these are implemented as an enumeration.  For
a contrived example:

enum color_t {
	// By convention, must begin with '0'
	RED = 0,
	GREEN,
	BLUE,
};

static const char *
colornames[] = {
	"Red",
	"Green",
	"Blue",
};

The head-scratcher lies in coding this in such a 
way that changes to color_t *automatically*
direct the developer to update colornames[].

And, to do so at compile-time, *not* run-time!

So, for example, adding "BEIGE" to color_t should,
at the very least, force a compiler error that
is easily/readily recognized as related to the
omission of the corresponding "Beige" entry from
colornames[].

There are some approaches that *approximate* this.
For example:

#if (sizeof(colornames[]) != COLOR_T_ENTRIES)
#  error "colornames[] does not have the correct \
   number of color_t entries"
#endif

except that sizeof() isn't valid during the
preprocesor phase (despite having encountered 
several compilers that don't realize this!  :> ).
And, of course, requiring  COLOR_T_ENTRIES to be
defined, by convention, as the last entry in the
enumeration.

So:

ASSERT(sizeof(colornames[]) == COLOR_T_ENTRIES)

but, this affects (trivially) the TEXT size *and*
deferes the test to *run*-time.

I can't see a *portable* way of doing this -- short
of writing a tool that writes the code defining the
table(s), etc.  (and I dislike trusting developers
to be diligent -- especially when it comes to
maintaining someone else's code  :<  )


Extra credit:  a scheme whereby the entries in
colornames[] can be assured to correspond to the
correct enumeration ordering WITHOUT PENALIZING
THE TEXT SIZE!   For example:

colornames[RED] = "Red";
colornames[BLUE] = "Blue";
colornames[BEIGE] = "Beige";

would "ensure" the correct entry is associated 
with each index.  But, it penalizes the TEXT size
*and* forces colornames[] to be DATA.  (it also
fails to ensure that *all* colornames[] entries
are defined).

Thx,
--don


       
____________________________________________________________________________________
Boardwalk for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's economy) at Yahoo! Games.
http://get.games.yahoo.com/proddesc?gamekey=monopolyherenow  




More information about the tfug mailing list