Misra violation 12.6

5.2k Views Asked by At

How to get rid of MISRA violation on following statement

typedef unsigned char boolean;

boolean A, B;

A = !B;

Operand of logical ! operator is not an 'effectively Boolean' expression. MISRA-C:2004 Rule 12.6; REFERENCE - ISO:C90-6.3.3.3 Unary Arithmetic Operators

5

There are 5 best solutions below

1
On

How about this:

A = (B == 0 ? 1 : 0);
4
On

Simple... don't use ! on things that aren't booleans. Just because your typedef is named boolean doesn't mean it is; it's still an unsigned char.

You could write:

if (b == 0) A = 1;
else A = 0;

I don't think MISRA allows ternary operators (could be wrong; not an expert) but if it does, you could write:

A = (b == 0) ? 1 : 0;
0
On

If you read rule 12.6 it says "check Boolean Expressions" in the appendix. There we can read

"Boolean-by-enforcement values can be introduced by implementing a specific type enforcement mechanism using a tool. A Boolean type could be associated with a specific typedef, and would then be used for any objects that are Boolean. This could bring many benefts, especially if the checking tool can support it, and in particular it could help avoid confusion between logical operations and integer operations."

MISRA-C:2004 assumes C90, and in C90 there is no bool type, you have to typedef it yourself, like you have done. Since your intention is to have a type which is effectively boolean, the code is just fine. In fact, your code follows MISRA recommendations beyond the mandatory ones.

The problem lies with your tool: it either does not support to allow a specific boolean type as per MISRA recommendations, or it is misconfigured.

6
On

Though the ISO:C90 standard says the operand can be of any scalar type the ! operator always yield a value of either 0 or 1; the underlying type (in MISRA-C:2004 terms) is considered effectively boolean, but the operand is not. Since the operator interprets its operand in a Boolean sense by comparing it 0 with try:

A = (B==0);

which make the logical comparison explicit. Also, depending on the tool, there may a boolean type enforcement mechanism you can configure for this typedef.

1
On

Have you tried the idiom !! to convert values in boolean:

bool bool_val = !!int_val;

Then the far-fetched following code might work:

A = !(!!B) // B is "cast" within the parenthesis then we apply the "NOT"