Struct (C programming language)
From Seo Wiki - Search Engine Optimization and Programming Languages
| This article does not cite any references or sources. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed. (December 2009) |
A struct in C programming language is a structured (record) type[1] that aggregates a fixed set of labelled objects, possibly of different types, into a single object.
A struct declaration consists of a list of fields, each of which can have any type. The total storage required for a struct object is the sum of the storage requirements of all the fields, plus any internal padding.
For example:
struct account { int account_number; char *first_name; char *last_name; float balance; };
defines a type, referred to as struct account. To create a new variable of this type, we can write
struct account s;
which has an integer component, accessed by s.account_number, and a floating-point component, accessed by s.balance, as well as the first_name and last_name components. The structure s contains all four values, and all four fields may be changed independently.
The primary use of a struct is for the construction of complex datatypes, but in practice they are sometimes used to circumvent standard C conventions to create a kind of primitive subtyping. For example, common Internet protocols rely on the fact that C compilers insert padding between struct fields in predictable ways; thus the code
struct ifoo_version_42 { long x, y, z; char *name; long a, b, c; }; struct ifoo_old_stub { long x, y; }; void operate_on_ifoo(struct ifoo_version_42 *); struct ifoo_old_stub s; . . . operate_on_ifoo(&s);
is often assumed to work as expected, if the operate_on_ifoo function only accesses fields x and y of its argument.
[edit] typedef
Typedefs can be (mis)used as shortcuts, for example:
typedef struct account_ { int account_number; char *first_name; char *last_name; float balance; } account;
Different users have differing preferences; proponents usually claim:
- shorter to write
However, there are a handful of disadvantages in using them:
- they pollute the main namespace (see below)
- harder to figure out the aliased type (having to scan/grep through code)
- typedefs do not really "hide" anything in a struct or union — members are still accessible (
account.balance)- (To really hide struct members, one needs to use 'incompletely-declared' structs.)
/* Example for namespace clash */ typedef struct account { float balance; } account; struct account account; /* possible */ account account; /* error */
[edit] References
- ↑ Ritchie, Dennis M. "The Development of the C Language". Second History of Programming Languages conference, Cambridge, Massachusetts, April, 1993. History of Programming Languages-II. ISBN 0-201-89502-1. http://plan9.bell-labs.com/who/dmr/chist.html.