Home > Blockchain >  Is it possible to typedef union inside a struct in C
Is it possible to typedef union inside a struct in C

Time:11-28

I don't really understand how union works. Can somebody explain how it works? Can I typedef the union? If the answer is yes, how can i do that? What is the problem with this code below?

typedef struct Car{
        int age;
        int weight;

        enum Type { Tesla, Lada } type;

        typedef union Consumption{
                double litre;
                int kwh;
        } Consumption;

        Consumption consumption;
} Car;

error code when i try to compile this code:

union1.c:9:2: error: expected specifier-qualifier-list before ‘typedeftypedef union Consumption{
  ^~~~~~~

CodePudding user response:

A typedef cannot exist inside of a struct or union. That doesn't mean however that you can't define a struct or union inside of another. For example:

typedef struct Car{
        int age;
        int weight;

        enum Type { Tesla, Lada } type;

        union Consumption{
                double litre;
                int kwh;
        } consumption;
} Car;
  • Related