Search code examples
c++arraysc-preprocessormisra

Define an array with #define command not complying with misra rules


I have this definition:

static const char* STRING_ARRAY[NUM_UNITS] = STRING_ARRAY_VALUES;

when

#define STRING_ARRAY_VALUES                 \
{   "n/a",                                  \
  "bool",                                   \
  ...                                       \
}

Unfortunately, it's not complying with MISRA-C++ Rule 8-5-2:

"MISRA-C++ Rule 8-5-2 (required): Braces shall be used to indicate and match the 
structure in the non-zero initialization of arrays and structures."

Can anyone please explain to me why it's not complying? I thought that the #define command turn the definition to something like:

static const char* STRING_ARRAY[NUM_UNITS] = {"n/a", "bool",...}

which is complying with MISRA rules.

Is there a way to make this to comply with MISRA while keeping the #define?


Solution

  • There are two possible causes:

    • Either your MISRA checker is broken. I tested your code with LDRA Testbed and it produces no errors.
    • Or I suppose NUM_UNITS possibly does not match the number of pointers passed to the array. It is not clear to me whether this is a violation of the MISRA rule or not. You could add a static assert that sizeof(STRING_ARRAY)/sizeof(const char*) == NUM_UNITS, which is good practice to do regardless of MISRA.