'C - forward declaration of enums?
Forward declaration of enums in C does not work for me. I searched the internet and Stack Overflow 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 a header) so that all functions in the file can access them?
Solution 1:[1]
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.
Solution 2:[2]
You can't "forward-declare" enums because the compiler won't know the size of the enum. The C standard says " Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-de?ned, but shall be capable of representing the values of all the members of the enumeration".
Solution 3:[3]
I came here having the same error, but there is not really much information provided here on the code/error.
My Makefile-flags are: -Wall -Wextra -Werror -pedantic -std=c17
In my header I have the following enum
:
typedef enum
{
IS_HEAD = 1,
IS_VALUE = 2,
IS_SIDE
} CoinResult;
Would recommend to use something like this:
enum CoinResult cr;
cr = IS_SIDE;
This results in the error stated by the OP.
Solved by using:
CoinResult cr = IS_SIDE;
Not sure which C-Standard, Code or reference OP was using, but I somewhat agree: Most tutorials and solutions for this relatively simple issue are kinda ambiguous.
Solution 4:[4]
CoinResult isn't an enum, it's a type. If you had
enum CoinResult {
IS_HEAD = 1,
IS_VALUE = 2,
IS_SIDE,
};
then
enum CoinResult cr;
would be correct.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Foo Bah |
Solution 3 | Qohelet |
Solution 4 | Guennadi Liakhovetski |