9Breaker
9Breaker

Reputation: 724

Coverity Static Analysis Saying Unsigned Int is Char (C++)

I am using Coverity to statically analyze some of our source code for a C++ project. I realize this may seem like a ridiculously simple question, but I figured if Coverity has an issue like this I want to know the underlying reason why this error is flagged. It keeps flagging an error and I want to know if this error is really something to change my coding practices for or if it is really unnecessary.

An example of the error it flags is:

unsigned int a;
a = 5;

Coverity has an issue with this and says:

"CID 101436 (#1 of 1): Implicit integer conversion (MISRA_CAST) integer_signedness_changing_conversion: MISRA-2004 Rule 10.1 violation: implicitly changing the signedness of an expression. Converting 5, with underlying type char (8 bits, signed), to type unsigned int (32 bits, unsigned) with different signedness."

Won't any modern compiler know that in the example above the 5 is an unsigned int and not a char? Is this really a valid error and could it ever cause errors with compilation? The error will go away as soon as I add:

unsigned int a;
a = 5U;

Is it really an issue if I don't specify the "U" after every unsigned int?

Upvotes: 1

Views: 1659

Answers (1)

Thomas Matthews
Thomas Matthews

Reputation: 57728

By definition, numeric integral constants without suffixes are signed quantities. You will either need to cast the constant or append the 'U' suffix.

The other issue is that constants are assigned the smallest type that will contain the value. For example, 5 fits into a int8_t or signed char. However, 260 is too big for a signed char, so its minimum type is int.

The second warning may go away after the signedness issue is resolved.

Upvotes: 3

Related Questions