Jump to content United States-English
HP.com Home Products and Services Support and Drivers Solutions How to Buy
» Contact HP
More options
HP.com home
HP C/HP-UX Reference Manual: HP-UX Systems > Chapter 3 Data Types and Declarations

Designated Initializer

» 

Technical documentation

Complete book in PDF
» Feedback
Content starts here

 » Table of Contents

 » Index

Designated initializer specifically initialize a particular member in a struct, union, or a particular element of an array. Designated initializer is a part of the C99 standards (ISO/IEC 9899:1999:6.7.8). Designated initializer eliminate the need to initialize the members of aggregates in order (from the first member onto the last in a structure and from the element indexed 0 to the last index in an array).

Designated initializer is of the form:

  • [const expression] - for an array element

  • .member - for a member of a struct or union

Examples

The following examples detail the usage of designated initializers in the C program:

Example 1: Initializing elements

int a[100] = {1,2,[50]=3,4,5,[23]=6,7};

In this example, designated initializers [50] and [23] are used to initialize elements in the middle of an array without initializing all the elements prior to them. The element a[50] contains the value 3 while a[51] is initialized to 4. Similarly, a[23]=6 and a[24]=7.

Example 2: Initializing selected members of a structure

struct node
{
int a;
int b;
char c[10];
};
struct node st = {.b=1,.c[4]=1,2,3,.a=4};

In this example, .b and .a initialize particular members of the structure st while the designated initializer.c[4] initializes a particular array element (index 4) of the structure member.c[4] with 1, c[5] with 2, and so on.

Example 3: Initializing union

union u
{
int x;
int c;
};
union u u1={.c=10};

In the above example, the order of initializing union members need not be followed using designated initializers.

Example 4: Initializing member-wise

struct st {
int a,b;
char c;
};
struct st s1={.a=1,.c=’x’,.b=10}; //new way
struct st s2={1, 10, ’x’}; //old way

The above example shows how member-wise initialization can be done using a structure and how initialization was done earlier.

Example 5: Initializing both array and structure

struct st{int a[5], b;};
struct st w[]={ [3]={1,2}, [1]={.a={[3]=1}, .b=1}
};

In this example, a combination of both array and structure are initialized. Here w[1].a[3] has a value of 1.

Example 6:Initializing an array

int a[5]={[2]=4, [0]=1,2,3}:

In the above example, a[2] is initialized to 3 but when compiled with +O3 and above, a[2] will be initialized to 4.

NOTE: Designated initializer is recognized in the ANSI extended (-Ae) mode only.
Printable version
Privacy statement Using this site means you accept its terms Feedback to webmaster
© Hewlett-Packard Development Company, L.P.