Re: C and MISRA, blues... (arithmetic shifts)





Steve at fivetrees wrote:

"Stefan Reuther" <stefan.news@xxxxxxxx> wrote in message
news:futb8o.e8.1@xxxxxxxxxxxxxxxxxxxxxxxx
Nils wrote:
But do you do if you need them anyway? I need *lots* of them, so in
despair I've just created this monster of unreadable code:

int ArithmeticShiftRight (int value, unsigned int shift)
{
/* Not sure whether that passes your MISRA checker: */
return (int) ((unsigned long long) value >> shift);
}

That aside, MISRA usually allows you to deviate from a rule if you
have
a good reason. This is to make you think about whether you really need
it. Arithmetic shifts would be a good thing to answer "yes" to that
question.

The function could finally even look like this:
int ArithmeticShiftRight (int value, unsigned int shift)
{
#if ((-1) >> 1) == -1
return value >> shift;
#else
# error Port me!
#endif
}
which would make your code portable under all practical definitions
known to me.

I totally agree - I do exactly this as a matter of routine. I strongly
encourage the use of macro-level platform traps which say "if this isn't
the platform I made allowances for and assumptions about, then yell -
don't just compile incorrectly".

I agree with the idea but be careful of the implementation.
The math executed in
#if ((-1) >> 1) == -1
is done so with the preprocessor and not the runtime
environment. They may not be the same.

I have seen two or three run time test routines written to
identify compiler features and how they work. This
would be a good place to use this type of code.
I will try to track down a url reference.

Walter..



.



Relevant Pages