Why should I use an enum member when assigning the same type to an enum variable in C?

I have the following:

typedef enum
{
   FLS_PROG_SUCCESS,
   FLS_PROG_FAIL,
   FLS_ERASE_SUCCESS2U,
   FLS_ERASE_FAIL,
   FLS_READ_SUCCESS,
   FLS_READ_FAIL,
   FLS_FORMAT_SUCCESS,
   FLS_FORMAT_FAIL
}FLS_JobResult_t;

void Foo(void)
{
   FLS_JobResult_t ProgramStatus;

   /* Then I try to initialize the variable value */
   ProgramStatus = FLS_PROG_SUCCESS;

   ...
}

      

Innocent uh, but when compiling MISRA C an error message is issued:

An expression value must not be assigned to an object with a narrower essential type or other category of an essential type

And I found out that I would write initialization like this:

ProgramStatus = (FLS_JobResult_t)FLS_PROG_SUCCESS;

      

And it just doesn't look good to me, he, like MISRA, wants me to throw throws all over the code and that's too much.

Do you know why this is? I don't think this should be a problem, but I've tried everything that comes to my mind and it was the only way to get rid of this error, but it just doesn't make any sense, does it?

Sincerely.

+3


source to share


1 answer


(Hi, this is a new account, so I can't use the comment section yet to ask for more clarification, so my answer may be wider than needed)

Based on the text of the warning message, I assume you are talking about MISRA-C: 2012 (the latest standard), which is a big improvement over the previous ones, in that there is much more effort in defining the rationale along with many more compatible and incompatible examples. were added. This is Rule 10.3, the rationale is that because C allows assignments between different arithmetic types to be performed automatically, using these implicit conversions can lead to unexpected results with the possibility of losing value, sign, or precision.

Thus, MISRA-C: 2012 requires the use of stronger typing as provided by its underlying type model, which reduces the likelihood of these problems occurring.



Unfortunately, many tools have incorrectly implemented the type rules and model. In this case, your tool is wrong, this is not a violation of the basic types of rules, because ProgramStatus

and FLS_PROG_SUCCESS

are the same basic type. In fact, a similar example is shown in the standard itself, in the list of rules for compatible examples:

enum enuma { A1, A2, A3   } ena;
ena  = A1;

      

If your seller of the instrument does not agree, you can post your question on the official MISRA forum to get an official answer and forward it to the supplier,

+6


source







All Articles