[RoarAudio] Why there is no valid way to do a forward decleration of an enum type in C

Philipp Schafft lion at lion.leolix.org
Mon Dec 5 12:28:46 CET 2011


flum,

For structs you may use forward declerations to hide internals or just
because of cicular dependencys of headers. This looks like this:

somefile.h:
 struct bla;
 void func(struct bla * ptr);
somefile.c:
 struct bla { ... };
 void func(struct bla * ptr) {
  ...;
 }

Or because of ciculary depends:
mainheader.h:
 #include <file0.h>
 #include <file1.h>
file0.h:
 struct blubb { ... };
 struct bla;
 struct blubb * func0(struct bla * ptr);
file1.h:
 struct bla { ... };
 struct bla * func1(struct blubb * ptr);

Now you may think this is possible with enum types as well? just replace
the 'struct' with 'enum', right? No.

This is because enum types are not always based on the same fundamental
type. It is right that it is based on an int but you can not be sure
wich one.

The compiler selects the best one depending on the real values of the
possible values as defined by the enum decleration and it's general
config. It may be signed or unsigned, it may be a normal int, a long int
or a short int. Maybe some compilers will also do long long int or other
strange stuff.

Here are some examples:
enum ex0 { A =  0, B = 5 };
enum ex1 { A = -1, B = 5 };
enum ex2 { A = 0x12345, B = A | 0x2 };

The first one will likely be based on 'unsigned int', the next one on
'signed int' and the last one will likely be 'unsigned long int'. This
of cause depends on the value range of the types your arch has.

In addition gcc can be forced to use short int (wich can be 1 byte long
on some archs) by using -fshort-enums.

The problem with the forward decleration is that the compiler does not
yet know the type the enum is basied on. So it does not even know the
size. It will likely fall back to an default type (seems to be 'unsigned
int' for gcc).

The big probelem with this is that passing such a type to a function or
storing a value in it may result in bad alignment of the function args
on stack or bad values. Both are critical errors which *will* corrupt
data.

From what I seen in the wild only one compiler (gcc on OpenBSD) warned
about it.

Thanks for reading. Happy hacking! If you have any comments, just
reply. :)

-- 
Philipp.
 (Rah of PH2)
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 482 bytes
Desc: This is a digitally signed message part
URL: <http://lists.keep-cool.org/pipermail/roaraudio/attachments/20111205/da1f0dd4/attachment.pgp>


More information about the RoarAudio mailing list