Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This noncompliant code example initializes an array of integers using an initialization with too many elements for the array.

Code Block
bgColor#FFCCCC
langc
int a[3] = {1, 2, 3, 4};

The size of the array a is 3, although the size of the initialization is 4. The last element of the initialization (4) is ignored. Most compilers will diagnose this error.

...

In this example, the compiler allocates an array of four integer elements and, because an array bound is not explicitly specified by the programmer, sets the array bound to 4. However, if the initializer changes, the array bound may also change, causing unexpected results.

Code Block
bgColor#FFCCCC
langc
int a[] = {1, 2, 3, 4};

Compliant Solution

This compliant solution explicitly specifies the array bound.

Code Block
bgColor#ccccff
langc
int a[4] = {1, 2, 3, 4};

Explicitly specifying the array bound, although it is implicitly defined by an initializer, allows a compiler or other static analysis tool to issue a diagnostic if these values do not agree.

...