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!
Hans,
I was referring to if I was receiving the ADC values in a s16 and everytime I wanted to use a u8, I had to shift the s16 (which is entirely impractical, since the adc values are only being stored in one place, rather than being updated in several). So yes, you are right, using it in the way you described shouldn't take significantly more space or time.
I was referring to if I was receiving the ADC values in a s16 and everytime I wanted to use a u8, I had to shift the s16
Same difference. I.e.: none. As long as you extract the same bits out of your s16, it makes no difference to properly optimized code whether you do it via a value-cast-shift-and-mask, a pointer cast, or a union hack. The end result is always the same thing: the high byte of that s16 object, so there's no reason why the compiled should be any different.
But if you don't believe me, you don't have to. Feel free to just try it out yourself.