Misra rule 19.7 : function like macro

7.8k views Asked by At

I have a warning regarding Misra rule 19.7 : A function should be used in preference to a function-like macro in the below line :

#define gOFFSETOF(type, mem) (gOFFSET)((size_t) ((char *)&((type *) 0)->mem - (char *)((type *) 0)))

how should I solve this ?

2

There are 2 answers

0
Veltas On BEST ANSWER

Rule 19.7 (advisory): A function should be used in preference to a function-like macro. While macros can provide a speed advantage over functions, functions provide a safer and more robust mechanism. This is particularly true with respect to the type checking of parameters, and the problem of function-like macros potentially evaluating parameters multiple times.

The rule is advisory, so this means it "should normally be followed":

Note that the status of "advisory" does not mean that these items can be ignored, but that they should be followed as far as is reasonably practical. Formal deviations are not necessary for advisory rules, but may be raised if it is considered appropriate.

So you have the option to break the rule without making a formal deviation.

Now, in answer to your question, "how should I solve this?", you have two choices given that this macro function can't be implemented as a function.

Option 1: deviate from rule 19.7

The advisory makes it clear that functions are nicer than macro functions, and cites the section in C Traps and Pitfalls, Andrew Koenig (1988) on comparing macro functions with functions, but describes it as a preference, and specifically over the short macro functions designed for "speed advantage".

If you believe this macro makes the code clearer, conciser, and you have suitably avoided the common pitfalls of macro functions, then you can deviate from rule 19.7 without making a formal specific deviation, and without failing compliance.

Option 2: remove the macro function

If after considering the advisory you deem it appropriate then remove the macro function. You may want to write more functions to break up the extra inline code, and/or avoid needless code duplication.

0
Lundin On

Rule 19.7 is advisory so you are free to ignore it, if you only document doing so in your compliance matrix. However, this is a very good rule and that macro is very unsafe. You should not write code like that in mission-critical software.

The best solution is indeed to do as MISRA says, avoid function-like macros, but instead write a real function. That way you get strong typing and safe code.