Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
C syntax
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Structures and unions=== ====Structures==== Structures and [[Union type|unions]] in C are defined as data containers consisting of a sequence of named members of various types. They are similar to records in other programming languages. The members of a structure are stored in consecutive locations in memory, although the compiler is allowed to insert padding between or after members (but not before the first member) for efficiency or as padding required for proper [[data structure alignment|alignment]] by the target architecture. The size of a structure is equal to the sum of the sizes of its members, plus the size of the padding. ====Unions==== Unions in C are related to structures and are defined as objects that may hold (at different times) objects of different types and sizes. They are analogous to variant records in other programming languages. Unlike structures, the components of a union all refer to the same location in memory. In this way, a union can be used at various times to hold different types of objects, without the need to create a separate object for each new type. The size of a union is equal to the size of its largest component type. ====Declaration==== Structures are declared with the [[struct (C programming language)|{{code|struct}}]] keyword and unions are declared with the {{code|union}} keyword. The specifier keyword is followed by an optional identifier name, which is used to identify the form of the structure or union. The identifier is followed by the declaration of the structure or union's body: a list of member declarations, contained within curly braces, with each declaration terminated by a semicolon. Finally, the declaration concludes with an optional list of identifier names, which are declared as instances of the structure or union. For example, the following statement declares a structure named {{code|s}} that contains three members; it will also declare an instance of the structure known as {{code|tee}}: <syntaxhighlight lang=C> struct s { int x; float y; char *z; } tee; </syntaxhighlight> And the following statement will declare a similar union named {{code|u}} and an instance of it named {{code|n}}: <syntaxhighlight lang=C> union u { int x; float y; char *z; } n; </syntaxhighlight> Members of structures and unions cannot have an incomplete or function type. Thus members cannot be an instance of the structure or union being declared (because it is incomplete at that point) but can be pointers to the type being declared. Once a structure or union body has been declared and given a name, it can be considered a new data type using the specifier {{code|struct}} or {{code|union}}, as appropriate, and the name. For example, the following statement, given the above structure declaration, declares a new instance of the structure {{code|s}} named {{code|r}}: <syntaxhighlight lang=C>struct s r;</syntaxhighlight> It is also common to use the <code>[[typedef]]</code> specifier to eliminate the need for the {{code|struct}} or {{code|union}} keyword in later references to the structure. The first identifier after the body of the structure is taken as the new name for the structure type (structure instances may not be declared in this context). For example, the following statement will declare a new type known as ''s_type'' that will contain some structure: <syntaxhighlight lang=C>typedef struct {...} s_type;</syntaxhighlight> Future statements can then use the specifier ''s_type'' (instead of the expanded {{code|struct}} ... specifier) to refer to the structure. ====Accessing members==== Members are accessed using the name of the instance of a structure or union, a period ({{code|.}}), and the name of the member. For example, given the declaration of ''tee'' from above, the member known as ''y'' (of type {{code|float}}) can be accessed using the following syntax: <syntaxhighlight lang=C>tee.y</syntaxhighlight> Structures are commonly accessed through pointers. Consider the following example that defines a pointer to ''tee'', known as ''ptr_to_tee'': <syntaxhighlight lang=C>struct s *ptr_to_tee = &tee;</syntaxhighlight> Member ''y'' of ''tee'' can then be accessed by dereferencing ''ptr_to_tee'' and using the result as the left operand: <syntaxhighlight lang=C>(*ptr_to_tee).y</syntaxhighlight> Which is identical to the simpler {{code|tee.y}} above as long as ''ptr_to_tee'' points to ''tee''. Due to [[Operators in C and C++#Operator precedence|operator precedence]] ("." being higher than "*"), the shorter <code>*ptr_to_tee.y</code> is incorrect for this purpose, instead being parsed as <code>*(ptr_to_tee.y)</code> and thus the parentheses are necessary. Because this operation is common, C provides an [[syntactic sugar|abbreviated syntax]] for accessing a member directly from a pointer. With this syntax, the name of the instance is replaced with the name of the pointer and the period is replaced with the character sequence {{code|->}}. Thus, the following method of accessing ''y'' is identical to the previous two: <syntaxhighlight lang=C>ptr_to_tee->y</syntaxhighlight> Members of unions are accessed in the same way. This can be chained; for example, in a linked list, one may refer to <code>n->next->next</code> for the second following node (assuming that <code>n->next</code> is not null). ====Assignment==== Assigning values to individual members of structures and unions is syntactically identical to assigning values to any other object. The only difference is that the ''lvalue'' of the assignment is the name of the member, as accessed by the syntax mentioned above. A structure can also be assigned as a unit to another structure of the same type. Structures (and pointers to structures) may also be used as function parameter and return types. For example, the following statement assigns the value of 74 (the ASCII code point for the letter 't') to the member named ''x'' in the structure ''tee'', from above: <syntaxhighlight lang=C>tee.x = 74;</syntaxhighlight> And the same assignment, using ''ptr_to_tee'' in place of ''tee'', would look like: <syntaxhighlight lang=C>ptr_to_tee->x = 74;</syntaxhighlight> Assignment with members of unions is identical. ====Other operations==== According to the C standard, the only legal operations that can be performed on a structure are copying it, assigning to it as a unit (or initializing it), taking its address with the address-of ({{code|&}}) unary operator, and accessing its members. Unions have the same restrictions. One of the operations implicitly forbidden is comparison: structures and unions cannot be compared using C's standard comparison facilities ({{code|1===}}, {{code|>}}, {{code|<}}, etc.). ====Bit fields==== C also provides a special type of member known as a [[bit field]], which is an integer with an explicitly specified number of bits. A bit field is declared as a structure (or union) member of type {{code|int}}, {{code|signed int}}, {{code|unsigned int}}, or {{code|_Bool}}<!-- Add bool and _BitInt(N) when updating the page for C23 -->,<ref group="note">Other implementation-defined types are also allowed. C++ allows using all integral and enumerated types and a lot of C compilers do the same.</ref> following the member name by a colon ({{code|:}}) and the number of bits it should occupy. The total number of bits in a single bit field must not exceed the total number of bits in its declared type (this is allowed in C++ however, where the extra bits are used for padding). As a special exception to the usual C syntax rules, it is implementation-defined whether a bit field declared as type {{code|int}}, without specifying {{code|signed}} or {{code|unsigned}}, is signed or unsigned. Thus, it is recommended to explicitly specify {{code|signed}} or {{code|unsigned}} on all structure members for portability. Unnamed fields consisting of just a colon followed by a number of bits are also allowed; these indicate [[data padding|padding]]. Specifying a width of zero for an unnamed field is used to force [[data structure alignment|alignment]] to a new word.<ref>Kernighan & Richie</ref> Since all members of a union occupy the same memory, unnamed bit-fields of width zero do nothing in unions, however unnamed bit-fields of non zero width can change the size of the union since they have to fit in it. The members of bit fields do not have addresses, and as such cannot be used with the address-of ({{code|&}}) unary operator. The {{code|sizeof}} operator may not be applied to bit fields. The following declaration declares a new structure type known as {{code|f}} and an instance of it known as {{code|g}}. Comments provide a description of each of the members: <syntaxhighlight lang=C> struct f { unsigned int flag : 1; /* a bit flag: can either be on (1) or off (0) */ signed int num : 4; /* a signed 4-bit field; range -7...7 or -8...7 */ signed int : 3; /* 3 bits of padding to round out to 8 bits */ } g; </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)