[Tfug] Developer question
Robert Hunter
hunter at tfug.org
Tue Jul 3 07:06:12 MST 2007
On 7/2/07, Bexley Hall <bexley401 at yahoo.com> wrote:
> 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:
Another possiblity is to use a struct to hold your symbolic constants,
and rely on a compiler warning to let you know when it is missing
initializers. The advantage would be that you could use arbitrary data
types for your constants, whereas you would be limited to a single data
type per array ( when using the "table" approach ).
<snip>
struct symbolic_constants {
char *red;
int green;
float blue;
};
/* works fine */
static const struct symbolic_constants SC1 = {
"Red",
42,
3.14
};
/* compiler warning about missing initializer */
static const struct symbolic_constants SC2 = {
"Red",
42,
};
</snip>
In C99 you can use "designated" initializers for structs. This is very
nice, because now you can specify your intializers in any order, and be
sure that they are being assigned to the correct field.
<snip>
/* C99 style "designated initializers" */
static const struct symbolic_constants SC1 = {
.blue = 3.14,
.green = 42,
.red = "Red",
};
</snip>
Unfortuantely, gcc does not seem to emit warnings about missing
initializers when using the "designated" syntax. Ah well, no extra
credit. ;-)
PS. You are talking about C and not C++, right?
--
Rob
More information about the tfug
mailing list