This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

MISRA C Union Workaround

Hello everyone,

I am writing some code using an 8051 device and I'm trying to make the code MISRA C compliant. One of the MISRA C rules is that unions are not allowed (and truthfully, I don't fully understand why the rule exists. I'm sure there's some way to abuse it that they're trying to avoid). Right now, I have a fairly basic union:

union
{ short s16; unsigned char u8[2];
} adcValue;

I know I can create some code updates to get around this (ie assign both values separately in code, only use one of the two datatypes and rely on shifts, etc to do this) but I was wondering if there is another MISRA C acceptable structure that might do the same thing (to avoid having to make some pretty large scale updates to my code).

Alternatively, I guess I could just make an exemption to this rule and document it but I wanted to understand my options before I decide one way or another and thought you guys might be able to provide me with some insight on the subject.

Any help you guys would be willing to give me would be greatly appreciated. Thanks!

Parents
  • I don't fully understand why the rule exists. I'm sure there's some way to abuse it that they're trying to avoid)

    Actually it's the other way round. Bascially all of the usual uses of unions are, actually, abuses. Hardly anyone ever uses unions within their specified limitations.

    The problem with your particular plan (like the vast majority of ways people try to apply unions) is that the language explicitly forbids it, by casting its second-strongest verdict: reading from any element of a union other than the one most recently written "yields an unspecified result". I.e. for all you can actually rely on, that code could give you the time-of-day on Mondays, or 13 on the 12th of any given month in the Chinese calender, and complet and utter random garbage the rest of the week; and you would have nobody but yourself to complain to.

Reply
  • I don't fully understand why the rule exists. I'm sure there's some way to abuse it that they're trying to avoid)

    Actually it's the other way round. Bascially all of the usual uses of unions are, actually, abuses. Hardly anyone ever uses unions within their specified limitations.

    The problem with your particular plan (like the vast majority of ways people try to apply unions) is that the language explicitly forbids it, by casting its second-strongest verdict: reading from any element of a union other than the one most recently written "yields an unspecified result". I.e. for all you can actually rely on, that code could give you the time-of-day on Mondays, or 13 on the 12th of any given month in the Chinese calender, and complet and utter random garbage the rest of the week; and you would have nobody but yourself to complain to.

Children