How to make (1 << 9) pass MISRA?
This question already has an answer here:
你也可以简单地通过使用来规避移位问题
#define MOTOR_ON ((uint16_t)512U) /* 1 << 9 = 2^9 */
My advice is to define a macro that hides the ugly casting, but then go ahead and do the ugly casting to make MISRA happy.
Something like:
#define LSHIFT(x, n)
(((unsigned int)(x)) << ((unsigned int)(n)))
Then in your actual code:
#define MOTOR_ON LSHIFT(1, 9)
EDIT: In a comment below, @Lundin says that MISRA will complain about function-like macros. I've never used MISRA so I didn't know that.
A quick Google search finds that MISRA has special comments you can add to your code to disable warnings. This suggests two possibilities:
In your header file where you define LSHIFT()
and RSHIFT()
and any other bit-manipulating macros, wrap the macro definitions in the MISRA warning disable comments.
In your source file where you want to put the bit-shifting, add MISRA warning disable comments and just put your code as you had it before.
http://www.gimpel.com/Discussion.cfm?ThreadMode=Prev&ThreadID=2261
If I'm understanding correctly, MISRA has global enable/disable but does not have disable followed by "put it back the way it was". So, the comments to disable and then enable will always globally enable the check, so ideally these magic comments shouldn't be in a header file.
So I guess my suggestion now is to put your original bit shifting code int a .C source file, and put the magic comments to disable/enable the MISRA warnings around the bit shifting code.
The value of expression is being assigned to an object with a narrower type. “1U << 9U” results in only preserving the low-order bits.
“Making MISRA happy” with ugly casting won't change this fact, though a poor tool might be gamed, it shouldn't.
The straightforward solution is to use an explicit cast :
#define MOTOR_ON ((uint16_t)0x200) /* 9th bit on turns on motor */
but if you believe the “shift is better for readability” then simply turn off the rule for this case and document the reasoning. The deviation process is perfectly fine (and encouraged) in MISRA compliant development, if fact complete conformance is impossible. You have to have a deviation management process to be fully compliant. Evidence of awareness is the goal, not evidence of conformance.
BTW, @Thomas, you are right, this is not an exact duplicate of MISRA C:2004, error with bit shifting which you also wrote. Though it is a Rule 10.3 violation, the concepts of “underlying type” described does little to help understand the intent of this warning for this specific question. My suggestion to all is taking a look at the description for Rule 10.3 in the latest version of MISRA-C:2012 (found here: http://misra.org.uk ) which makes the concepts and intent much more clear for engineers and tool makers.
链接地址: http://www.djcxy.com/p/77166.html上一篇: 优化HTML表格?
下一篇: 如何使(1 << 9)通过MISRA?