Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to typedef union inside a struct in C

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 ‘typedef’
  typedef union Consumption{
  ^~~~~~~

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading