HP C A.06.05 Reference Manual
Data Types and Declarations
Initialization
Chapter 364
When initializing the members of an aggregate, the initializer is a brace-enclosed list of
initializes. In the case of a structure with automatic storage duration, the initializer may be a
single expression returning a type compatible with the structure. If the aggregate contains
members that are aggregates, this rule applies recursively, with the following exceptions:
• Inner braces may be optionally omitted.
• Members that are themselves aggregates cannot be initialized with a single expression,
even if the aggregate has automatic storage duration.
In ANSI mode, the initializer lists are parsed top-down; in compatibility mode, they are
parsed bottom-up. For example,
int q [3] [3] [2] = {
{ 1 }
{ 2, 3 }
{ 4, 5, 6 }
};
produces the following layout:
ANSI Mode Compatibility Mode
1 0 0 0 0 0 1 0 2 3 4 5
2 3 0 0 0 0 6 0 0 0 0 0
4 5 6 0 0 0 0 0 0 0 0 0
It is advisable to either fully specify the braces, or fully elide all but the outermost braces,
both for readability and ease of migration from compatibility mode to ANSI mode.
Because the compiler counts the number of specified initializes, you do not need to specify the
size in array declarations. The compiler counts the initializes and that becomes the size:
int x[ ] = {1, 10, 30, 2, 45};
This declaration allocates an array of int called x with a size of five. The size is not specified in
the square brackets; instead, the compiler infers it by counting the initializes.
As a special case, you can initialize an array of characters with a character string literal. If
the dimension of the array of characters is not provided, the compiler counts the number of
characters in the string literal to determine the size of the array. Note that the terminating \0
is also counted. For example:
char message[ ] = "hello";
This example defines an array of characters named message that contains six characters. It is
identical to the following:
char message[ ] = {'h','e','l','l','o','\0'};
You can also initialize a pointer to characters with a string literal: