Question

I'm trying to use Enums within a struct, this compiles and works fine with gcc. But the same code when compiled with g++ throws an error.

#include<stdio.h>
#include<stdlib.h>
struct foo
{
    enum {MODE1, MODE2, MODE3} mode;
    enum {TYPE1, TYPE2} type;
};
void bar(struct foo* bar)
{
    bar->mode = MODE1;
}

int main()
{
    struct foo* foo = (struct foo*) malloc(sizeof(struct foo));
    bar(foo);
    printf("mode=%d\n",foo->mode);
}

Output obtained with gcc:

 $ gcc foo.c
 $ ./a.out
 mode=0

Output obtained with g++:

 $ g++ foo.c
 foo.c: In function ‘void bar(foo*)’:
 foo.c:11: error: ‘MODE1’ was not declared in this scope
Était-ce utile?

La solution

MODE1 is in the scope of foo, so you need

bar->mode = foo::MODE1;

Note that if you want to access the enum types without a scope, you would need to declare them so. For example:

typedef enum {MODE1, MODE2, MODE3} MODE;
typedef enum {TYPE1, TYPE2} TYPE;

struct foo
{
    MODE mode;
    TYPE type;
};
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top