简体   繁体   中英

Ternary operator argument evaluation in C

I've been working with some code to ensure MISRA compliance. The issue with this piece of code is

Operands shall not be of an inappropriate essential type. The operand of the ? operator is of an inappropriate essential type category unsigned. 

I assume the issue is with the first argument being an unsigned data type, instead of boolean, which means the fix bellow would work.

The original,

 return (uint32Var & 0x80000000u) ? 0u : 1u;

My change to the code,

 return ( (uint32Var & 0x80000000u)!=0u ) ? 0u : 1u;

Is this a correct change to make? I'm concerned about changing the functionality of the code but as far as I know, at least in if logic, the operand is evaluated as numVar != 0 inside the if ( numVar ) operator.

That is safe.

You'll be comparing the unsigned 32-bit:

(uint32Var & 0x80000000u)

To the unsigned int :

0u

Usual arithmetic conversions apply to ensure that regardless of the actual types involved here, you'll be comparing values of types that are at least large enough to contains unsigned 32-bit.

The value (uint32Var & 0x80000000u) is a false one if it is equal to 0 , otherwise it is a true one. Comparing the value to 0 has the effect, and yielding 0 if the comparison is equal, otherwise yielding 1 is equivalent behavior.


As another note, the value that you end up using for the first operand of the ternary operator isn't a bool , it's an int . The != operator yields an int value of either 0 or 1 .

I assume the issue is with the first argument being an unsigned data type, instead of boolean, which means the fix bellow would work. /--/

Is this a correct change to make?

Yes. As in, it will make the code MISRA compliant. The warning is indeed about using a non-boolean type for the 1st operand.

However, assuming that the function returns uint32_t , you may as well just write:

return (uint32_t) !(uint32Var & mask);

( mask since MISRA, like everyone else, discourages the use of "magic numbers".)

Equivalent and also MISRA-C compatible:

return ~uint32Var >> bits; // where bits in this case is 31

Normally the ~ operator is a nasty piece when writing MISRA compilant code, but it is perfectly safe when you use an unsigned integer type which is not a small integer type, such as uint32_t .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM