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;
Lundin
  • 195,001
  • 40
  • 254
  • 396
crj11
  • 197
  • 7
  • 2
    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) – Bernd Elkemann Feb 27 '19 at 05:50
  • 1
    since we dont work there we cant be 100% sure, so this is primarily opinion based. But I assume it was for consistency. – old_timer Feb 27 '19 at 22:33
  • 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. – old_timer Feb 27 '19 at 22:34

1 Answers1

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.

Lundin
  • 195,001
  • 40
  • 254
  • 396