Home > Software engineering >  Is it possible to declare unions inside of a structure in C?
Is it possible to declare unions inside of a structure in C?

Time:01-12

I wanted to shorten my code, the code's purpose is to control stepper motors. I want to hold the ammount of steps (32 bits) and the frequency of rotation (16 bits). I receive this information through a bus in a uint8_t format. My idea was to not have to multiply each bit by 256/65535.... to make up the steps and frequency. I can do this with unions, but I also want to have multiple motors, so I decided to declare a structure for that and have the unions inside. It keeps giving me errors, so I am obviously doing something incorrectly.

I expected that declaring the unions inside the structure would not be an issue, as unions take up the memory space equal to it's largest member, it seemed reasonable that they could be structure elements. Here is a code snippet:

struct Stepper_Motor
  {
        union Num_Steps
        {
            uint32_t Sum_Steps;
            uint8_t Arr_Steps[4];
        };

        union Rotation_freq
        {
            uint16_t Sum_Freq;
            uint8_t Arr_Freq[2];
        };

        uint8_t State;
  };

When I try to access the struct members after declaring it, the IDE gives me a list of the members of the structure, when I write one of them down:

```
struct Stepper_Motor Motor1,Motor2,Motor3;

//Some code... //

Motor1.Arr_Freq[0] = something;  // this gives me an error,  "no members named Arr_Freq"
```

I also tried the following:

Motor1.Rotation_freq.Arr_Freq[0] = something;  //error

Is it even possible to do what I want? Do I have to declare the unions outside the structure then refer to them inside of it, if so, how? Is this a bogus way of using unions, to save on having to write multiplications?

CodePudding user response:

If you remove the tag name from the unions so that they're anonymous:

struct Stepper_Motor
{
        union
        {
            uint32_t Sum_Steps;
            uint8_t Arr_Steps[4];
        };

        union
        {
            uint16_t Sum_Freq;
            uint8_t Arr_Freq[2];
        };

        uint8_t State;
};

Then the union members will appear as members of the struct.

  • Related