Re: [gtk-list] #define vs enum



"K. Richard Pixley" <rich@kyoto.noir.com> writes:

> I notice that in the glib/gdk/gtk headers there are some #define's of
> constants.  I'd like to suggest that this is perhaps BadPractice(tm),
> or at least NonOptimal(tm).
> 
> We've already committed to an ansi C compiler by using naked
> prototypes in the headers.  The only reasons to use #define's for
> constants is either to patronize old or broken compilers, or to save a
> coupla bytes in embedded apps.
> 
> If we're committed to ansi, then the old/broken compiler consideration
> is a non-issue.  In which case, enum's are a better bet than #define's
> for two main reasons.
> 
> 1) they can be type checked, avoiding many cast requirements, and
>    offering compiler support correct usage.
> 
> 2) the value of an enum token is embedded in the object file and can
>    be printed with a debugger.
> 
> For the honest-to-goodness single stray constant, "const" is a
> possible alternative.  It allows the debugger to print the value,
> though it costs a few bytes in the data section to do so.
> 
> If there's clear agreement on enums, then I'll volunteer to make the
> changes throughout glib/gdk/gtk/gimp, and maybe even gnome.

 Ok here is an alternate viewpoint, and this is all from memory and I
don't use enums so feel free to correct me.

 C is 2 languages. #define's can be used in both enum's can't.

 Because of the above you can do gcc -E file | less as a very easy way 
to find out a value.

 #define's _can_ be printed while debugging, it's just that gcc
doesn't support it (yet, there was discussion on the egcs list to put
the functionality in).

 Contrary to what you might hope the named enums are useless.
Ie.

enum abcd
{
 ONE = 1 
};

typedef enum defg
{
 TWO = 2
} defg;

int main(void)
{
 defg foo = TWO;

 exit (EXIT_SUCCESS);
}

 The above is perfectly valid C/C++ code and you won't get a warning.
 Also if you move the defg foo out of main, then it will generate an
error in C as you can't initalise static/global identifiers to enum
values within the current standard (this should be fixed in the next
C standard afaik).
 Also if you are going to generate code automatically then you need to
support a head and tail case for enum's (in the current standard you
can't just put ,'s on the end of all lines like you can with arrays.

-- 
# James Antill -- jamesa@demon.net
:0:
* ^From: .*jamesa@demon.net
/dev/null



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]