Friday, July 29, 2016

C Basics - Incomplete Type in C

An incomplete type is a struct or union type whose members have not yet been specified, an array type whose dimension has not yet been specified, or the void type (the void type cannot be completed). Such a type may not be instantiated (its size is not known), nor may its members be accessed (they, too, are unknown); however, the derived pointer type may be used (but not dereferenced).

They are often used with pointers, either as forward or external declarations. For instance, code could declare an incomplete type like this:

struct thing *pt;

This declares pt as a pointer to struct thing and the incomplete type struct thing. Pointers always have the same byte-width regardless of what they point to, so this statement is valid by itself (as long as pt is not dereferenced). The incomplete type can be completed later in the same scope by redeclaring it:

struct thing {
    int num;
}; /* thing struct type is now completed */

Incomplete types are used to implement recursive structures; the body of the type declaration may be deferred to later in the translation unit:

typedef struct Bert Bert;
typedef struct Wilma Wilma;

struct Bert {
    Wilma *wilma;
};

struct Wilma {
    Bert *bert;
};

Incomplete types are also used for data hiding; the incomplete type is defined in a header file, and the body only within the relevant source file.



Related topics:
Memory Management in C   |   Incomplete Type in C   |   Lifetime, Scope, Visibility and Linkage in C   |   Namespace in C   |   Complex and Abstract Declarations in C   |   Storage of Data Types in C   |   Standard Library in C

List of topics: C Programming

No comments:

Post a Comment