Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerations within a struct - C vs C++

Tags:

c++

c

enums

gcc

struct

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
like image 690
arunmoezhi Avatar asked May 04 '14 22:05

arunmoezhi


1 Answers

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;
};
like image 200
juanchopanza Avatar answered Oct 16 '22 18:10

juanchopanza