Saturday, May 22, 2010

Initializing Variables in C

C allows variables to be initialized in the declaration statement. For example, the

following statement declares the integer counter and initializes it to 0:

int counter = 0; /* number cases counted so far */

Arrays can also be initialized in this manner. The element list must be enclosed in

curly braces ({}). For example:

/* Product numbers for the parts we are making */

int product_codes[3] = {10, 972, 45};

The previous initialization is equivalent to:

product_codes[0] = 10;

product_codes[1] = 972;

product_codes[2] = 45;

The number of elements in {} does not have to match the array size. If too many

numbers are present, a warning will be issued. If an insufficient amount of numbers

are present, C will initialize the extra elements to 0.

If no dimension is given, C will determine the dimension from the number of

elements in the initialization list. For example, we could have initialized our variable

product_codes with the state ment:

/* Product numbers for the parts we are making */

int product_codes[] = {10, 972, 45};

Initializing multidimensional arrays is similar to initializing single-dimension arrays.

A set of brackets ([ ]) encloses each dimension. The declaration:

int matrix[2][4]; /* a typical matrix */

can be thought of as a declaration of an array of dimension 2 with elements that are

arrays of dimension 4. This array is initialized as follows:

/* a typical matrix */

int matrix[2][4] =

{

{1, 2, 3, 4},

{10, 20, 30, 40}

};

Strings can be initialized in a similar manner. For example, to initialize the variable

name to the string "Sam", we use the statement:

char name[] = {'S', 'a', 'm', '\0'};

C has a special shorthand for initializing strings: Surround the string with double

quotes ("") to simplify initialization. The previous example could have been written:

char name[] = "Sam";

The dimension of name is 4, because C allocates a place for the '\0' character that

ends the string.

The following declaration:

char string[50] = "Sam";

is equivalent to:

char string[50];

.

.

.

strcpy(string,"Sam");

An array of 50 characters is allocated but the length of the string is 3.

Source: Practical C Programming, Third Edition - O'Reilly Media

No comments:

Post a Comment