1.8 Declarations

A declaration determines the interpretation and properties of one or more identifiers. A declaration that allocates storage space for an object or a function is a definition. In C, an object is a data storage region that contains constant or variable values. The term "object" is thus somewhat more general than the term "variable."

In the source file, declarations can appear at the beginning of a block, such as a function block, or outside of all functions. Declarations that do not allocate storage space, such as function prototypes or type definitions, are normally placed in a header file.

ANSI C99 allows declarations and statements to appear in any order within a block.

1.8.1 General Syntax and Examples

The general syntax of a declaration is as follows:

[storage class] type  D1 [, D2, ...];

storage class

One of the storage class specifiers extern, static, auto, or register.

type

A basic type, or one of the following type specifiers: void, enum type (enumeration), struct or union type, or typedef name.

type may also contain type qualifiers, such as const.

D1 [, D2,...]

A list of declarators. A declarator contains at least one identifier, such as a variable name.

Some examples are:

char  letter;
int   i, j, k;
static  double rate, price;
extern char  flag;

Variables can be initialized—that is, assigned an initial value—in the declaration. Variable and function declarations are described in detail in the sections that follow.

1.8.2 Complex Declarations

If a declarator contains only one identifier, with or without an initialization, the declaration is called a simple declaration. In a complex declaration, the declarator also contains additional type information. This is necessary in declarations of pointers, arrays, and functions. Such declarations use the three operators, shown in Table 1-17.

Table 1-17. Operators for complex declarations

Operator

Meaning

*

Pointer to

[ ]

Array of element type

( )

Function returning value of type

The operators in Table 1-17 have the same precedence in declarations as in expressions. Parentheses can also be used to group operands.

Complex declarators are always interpreted beginning with the identifier being declared. Then the following steps are repeated until all operators are resolved:

1.       Any pair of parentheses () or square brackets [] appearing to the right is interpreted.

2.       If there are none, then any asterisk appearing to the left is interpreted.

For example:

char *strptr[100];

This declaration identifies strptr as an array. The array's 100 elements are pointers to char.