Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - forward declaration of enums?

Forward declaration of enums in C does not work for me. I searched the internet and stackoverflow but all of the questions regarding forward declarations of enumerators refer to c++. What do you do for declaring enumerators in C? Put them at the top of each file (or in an include) so that all functions in the file can access them? Thanks

like image 592
loop Avatar asked Sep 20 '11 04:09

loop


People also ask

Can you forward declare enum?

Forward Declaration of Enums (C++11) BCC32 introduces forward declaration of enums. You can declare an enumeration without providing a list of enumerators. Such declarations would not be definitions and can be provided only for enumerations with fixed underlying types.

Can you forward declare in C?

In Objective-C, classes and protocols can be forward-declared if you only need to use them as part of an object pointer type, e.g. MyClass * or id<MyProtocol>.

How do you declare an enum variable?

An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.

Can you forward declare a return type?

Return type does not match forward declaration: <function name> Change the data type of the return value in the declaration or in the corresponding definition so that they match.


1 Answers

Put them in a header so that all files that need them can access the header and use the declarations from it.

When compiled with the options:

$ /usr/bin/gcc -g -std=c99 -Wall -Wextra -c enum.c
$

GCC 4.2.1 (on MacOS X 10.7.1) accepts the following code:

enum xyz;

struct qqq { enum xyz *p; };

enum xyz { abc, def, ghi, jkl };

Add -pedantic and it warns:

$ /usr/bin/gcc -g -std=c99 -Wall -Wextra -pedantic -c enum.c
enum.c:1: warning: ISO C forbids forward references to ‘enum’ types
enum.c:5: warning: ISO C forbids forward references to ‘enum’ types
$

Thus, you are not supposed to try using forward declarations of enumerated types in C; GCC allows it as an extension when not forced to be pedantic.

like image 131
Jonathan Leffler Avatar answered Sep 24 '22 19:09

Jonathan Leffler