Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
758 views
in Technique[技术] by (71.8m points)

c - How are integer types converted implicitly?

The following code fails on a MISRA check. The concrete error message is:

(MISRA-C:2004 10.1/R) The value of an expression of integer type shall not be implicitly converted to a different underlying type if it is not a conversion to a wider integer type of the same signedness

typedef enum _MyEnum { One, Two } MyEnum;
MyEnum MyVariable;

int foo(void)
{
    int result = 1;

    if (One == MyVariable)  // fails here with MISRA-C:2004 10.1/R
    {
        result = 2;
    }    
    return result;
}
  • Why is the logical expression converted?
  • What is converted here?
  • Why does the code pass the MISRA check, when I swap One and MyVariable?

Edit: The compiler is a TI "MSP430 C/C++ Compiler v4.0.0" with included MISRA rules check.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no bug in the MISRA checker, it behaves correctly. You get this error because the C standard is flawed and illogical.

There are two items:

  • One is an enumeration constant. The standard §6.7.2.2/2 states that this shall be compatible with int, no exceptions.

  • MyVariable is an enumerated type. The standard §6.7.7.2/4 states that this should be compatible with char, a signed integer type or an unsigned integer type. Which type that applies is implementation-defined behavior.

In your case, the implementation-defined enumerated type appears to be equal to unsigned int.

So the code attempts to implictly convert a variable of signed int to unsigned int, which is a violation of MISRA 2004 10.1.

MISRA-compliant code should be if (One == (MyEnum)MyVariable).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...