[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

MISRA C Rule 20.7 disambiguation



Hi all,

This patch is to start a discussion in regard to rule 20.7 and its
interpretation. During the last MISRA C call we discussed that "our"
interpretation of the rule means that the following two cases don't need
extra parenthesis:

#define M(a, b) func(a, b)
#define M(a, b) (a) = b


Moreover, MISRA C states that parenthesis should be added when the
expansion of a MACRO parameters would result in an *expression*.

Expression is the important word. Looking at this *compliant* example
from the manual:

#define GET_MEMBER( S, M ) ( S ).M

It is compliant because S results in an expression so it needs
parenthesis, while M does not, so it doesn't need parenthesis.

My understanding is the following:
- is it possible to pass an expression as a parameter of the MACRO?
    - if yes -> need parenthesis
    - if no  -> doesn't need parenthesis


As an example, cppcheck reports the following (from xmalloc.h) as
violation:

#define xmalloc_array(_type, _num) \
    ((_type *)_xmalloc_array(sizeof(_type), __alignof__(_type), _num))

I think this is a false positive. We have already enstablished that the
"," operator doesn't require parenthesis, so "_num" is not the problem.
And there is no way that adding parenthesis to "type" would allow an
expression to be passed as the type argument.


Let's take another example:

#define xzalloc_flex_struct(type, field, nr) \
    ((type *)_xzalloc(offsetof(type, field[nr]), __alignof__(type)))

"type" is the same as last time. There are 2 other interesting macro
parameters here: nr and field.

nr could result in an expression, but I don't think it needs
parenthesis because it is between []? However, we know we have a clear
exception for the "," operator. We don't have a clear exception for the
[] operator. Do we need (nr)?

field could result in an expression, so I think it needs parenthesis.

Just to be clear, I'll list all the possible options below.

a) no changes needed, xzalloc_flex_struct is good as is
b) only "field" needs parenthesis
c) only "nr" needs parenthesis
d) both "field" and "nr" need parenthesis

Option d) would look like this:

#define xzalloc_flex_struct(type, field, nr) \
    ((type *)_xzalloc(offsetof(type, (field)[(nr)]), __alignof__(type)))

What do you guys think?

Cheers,

Stefano



 


Rackspace

Lists.xenproject.org is hosted with RackSpace, monitoring our
servers 24x7x365 and backed by RackSpace's Fanatical Support®.