Enumerations within a structure - C vs C ++

I am trying to use enums inside a structure, and this compiles and works fine with gcc. But the same code when compiling with an g++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 for gcc

-bash-4.1$ gcc foo.c
-bash-4.1$ ./a.out
 mode=0

Output for g ++

-bash-4.1$ g++ foo.c
 foo.c: In function ‘void bar(foo*)’:
 foo.c:11: error: ‘MODE1’ was not declared in this scope
+4
source share
1 answer

MODE1is in the area fooso you need

bar->mode = foo::MODE1;

Note that if you want to access enumeration types without scope, you need to declare them like this. For instance:

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

struct foo
{
    MODE mode;
    TYPE type;
};
+5
source

Source: https://habr.com/ru/post/1539195/


All Articles