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!
"... 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"."
That's certainly the case for C51 being pre-C99 (TC3).
If I'm not misinterpreting a footnote added in 2007's C99 TC3, there may be, shall I say, some "wiggle room". TC3 still has the "unspecified values" in 6.2.6.1 par.7 and "unspecified behavior" in Annex J.1, but 6.5.2.3 par.3 now has footnote 82:
"If the member used to access the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called "type punning"). This might be a trap representation."
Of course, note the last sentence is a caveat.
The footnote sends a bit of a mixed message, I think, what with "unspecified" still hanging around elsewhere.