Domanda

I have the following line (reduced to minimally demonstrate issue):

char version_text[64U] = {'\0'};

This line generates the following MISRA error:

Error[Pm023]: missing elements - braces shall be used to indicate and match the structure in the non-zero initialization of arrays and structures (MISRA C 2004 rule 9.2).

Why is this an error?

My current workaround is:

char version_text[64U] = {0};

which indicates that the char type is implemented as signed char by my compiler (IAR EW).

My understanding is that '\0' is a character literal and thus, should match the type char.

È stato utile?

Soluzione

In C, integer character constants have the type int, not char. So

char version_text[64U] = { '\0' };

and

char version_text[64U] = { 0 };

are completely equivalent (and that is independent of the signedness of char). Both provide an int constant as the sole initialiser.

That the MISRA checker complains about the first, but not the second is just an inconsistency.

However, it is probably due to the fact that a zero-initialisation is customarily done by providing just one 0, while using integer character constants is usually only done for non-zero initialisations - where MISRA expects initialisers for all elements, if I interpret the message correctly, and the checker just doesn't look inside the character constant.

Altri suggerimenti

The rule says:

"Note also that all the elements of arrays or structures can be initialised (to zero or NULL) by giving an explicit initialiser for the first element only. If this method of initialisation is chosen then the first element should be initialised to zero (or NULL), and nested braces need not be used."

According to this, only {0} and {NULL} are compliant with MISRA, and {'\0'} isn't (even though the compiler treats them in the same way).

Try with the following:

char version_text[64U] = { '\0', };

This essentially will initialize each array element to NULL not only the first one. Notice a comma!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top