Why do I have to cast an enum element when assigning it to a same enum variable type in C?

这一生的挚爱 提交于 2019-12-12 13:15:00

问题


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 gives the error:

The value of an expression shall not be assigned to an object with a narrower essential type or of a different essential type category

And I found out that I shall write the initialization as follows:

ProgramStatus = (FLS_JobResult_t)FLS_PROG_SUCCESS;

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

Do you know why is this? I don't think this should be an issue but I've tried everything that comes to my mind and this was the only way of getting rid of this error, but it simply does not make any sense, does it?

Regards.


回答1:


(Hi, this is a new account so I cannot use the comments section yet to ask for further clarification, so, my answer may be broader 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 great improvement over the prior ones in that much more effort in stating the rationale along with many more compliant and non-compliant examples have been added. This being Rule 10.3, the rationale is: since C permits assignments between different arithmetic types to be performed automatically, the use of these implicit conversions can lead to unintended results, with the potential for loss of value, sign or precision.

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

Unfortunately many tools have not properly implemented the rules and the type model. In this case, your tool is incorrect, this is not a violation of essential type rules because ProgramStatus and FLS_PROG_SUCCESS are both the same essential type. In fact a similar example is shown in the standard itself, under the rule’s list of compliant examples:

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

If your tool vendor disagrees you can post your question on the "official" MISRA forum to get the official answer and forward that to the vendor.



来源:https://stackoverflow.com/questions/31729670/why-do-i-have-to-cast-an-enum-element-when-assigning-it-to-a-same-enum-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!