Is there any difference between the members of this C union?
Asked Answered
L

1

6

The typedef below is for the DIR register from the Atmel SAMD21 ARM MCU include file. Since the bit struct member and the reg member are both 32 bits, is there any difference between the two members in the union?

I'm trying to understand why they did not just use a uint32_t as the type for the DIRSET register. My only thought that they just defined it this way to be consistent with other registers where there are multiple fields within the bit struct.

typedef union {
    struct {
        uint32_t DIRSET:32;
    } bit;
    uint32_t reg;
} PORT_DIRSET_Type;
Live answered 27/2, 2019 at 4:56 Comment(3)
The consistency is probably needed to write macros. Also it might be possible that some platforms can work with unaligned uint32's but can't work with unaligned uint32 bitfields? (Adding an alignment-attribute would force other platforms to obey it even though they don't need it)Hillie
since we dont work there we cant be 100% sure, so this is primarily opinion based. But I assume it was for consistency.Waal
you should avoid code that uses this union cr@p , which unfortunately means toss out cmsis and vendor libraries...and or fix them before you use them.Waal
K
7

From a general point of view, it's just code bloat - there is no reason why you would ever want to write code like that. However, the ASF coding style is that every register access ends with .reg, so that's the reason here: they want to keep register naming and use consistent.

They could of course just have done that with typedef struct { uint32_t reg; } PORT_DIRSET_Type but this code base is rarely ever rationally written. It could have been automatically generated through some script.

As a rule of thumb, register maps like these are always horribly ugly and non-portable, filled with irrational code. Those shipped as part of ASF are some of the worst I've ever seen all categories.

Kourtneykovac answered 27/2, 2019 at 8:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.