Page 1 of 1

Rule 10.3 - Bitfield narrower essential type

Posted: Thu Oct 24, 2019 7:01 am
by apereira
Hello,

Assuming that I have the following structure and enum:

Code: Select all

  typedef struct s{
  unsigned int a:5;
  unsigned int b:1;
  unsigned int c:1;
} s;

typedef enum e{
  ZERO = 0,
  ONE = 1,
  TWO = 2,
  THREE = 3
} e;
Why does the following code trigger rule 10.3?

Code: Select all

s fcn(void)
{
  s test;

  test.a = (unsigned int) THREE;

  return test;
}

Re: Rule 10.3 - Bitfield narrower essential type

Posted: Wed Nov 27, 2019 9:54 am
by misra-c
This response assumes an 8-bit char, 16-bit short and 32-bit int.

The essential type for bit-fields is explained in appendix D.4. It is the smallest standard type which is able to represent all possible values of the bit-field.
Therefore the essential type for test.a is "unsigned char".

The essential type of "(unsigned int)THREE" is "unsigned int" as the cast operation is not listed in Appendix D.7.

There is therefore a "narrower conversion" from "unsigned int" to "unsigned char" and hence a violation of rule 10.3.

The following would be valid with this rule:

Code: Select all

test.a = (unsigned char)THREE;