Re: #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).

Just so that nobody gets the wrong idea, this is very rare.

I can find just a few places:

 - The priorities GTK_PRIORITY_HIGH/_LOW/_INTERNAL in gtkmain.h
 - GDK_NONE: A special atom. (atoms are uints)
 - GDK_CURRENT_TIME: A special time.
 - GDK_PARENT_RELATIVE: A special pointer value

 - The defines in gdkkeysyms.h. (Autogenerated from X header files,
   I'm not sure what a 1300 element enumeration would do to some
   C compilers)
 - various defines in fnmatch.h (A header from elsewhere, not installed)
 - various defines in MwmUtil.h (A header from LessTif, not installed)

The first four items are used as special integers, points, or guints,
so you get no real benefits by making them enumerations. (Not for
type safety and mostly not for the debugger)

I have some worries about making a 1300 item enumeration for
gdkkeysyms.h, though it is otherwise a good candidate.

I don't think fnmatch.h and MwmUtil.h should be changed. 

> 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.

Anonymous enumerations are already used extensively in GTK code.
ANSI-ness is not an issue here.
 
> 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.

I don't paricularly like the 'const' solution, since it will prevent
most compilers from inlining the constants. (Unless you just make it
'static const int xxx = blah' in the header files which costs a few bytes for
every object file. For a few stray constants (most of which are 0
anyways), I think #define isn't that bad a solution.

> If there's clear agreement on enums, then I'll volunteer to make the
> changes throughout glib/gdk/gtk/gimp, and maybe even gnome.

Well, for GLIB/GDK/GTK I don't think there are enough to really
worry about much one way or the other.

Regards,
                                        Owen



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