Search code examples
carraysarray-initializationmisra

Initializing char arrays and MISRA errors


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.


Solution

  • 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.