分类: C/C++
2011-03-30 21:39:31
Enumerations create new data types to contain something different that is not limit to the values fundamental data types may take. Its form is the following:
enum enumeration_name { |
For example, we could create a new type of variable called colors_t to store colors with the following declaration:
enum colors_t {black, blue, green, cyan, red, purple, yellow, white}; |
Notice that we do not include any fundamental data type in the declaration. To say it somehow, we have created a whole new data type from scratch without basing it on any other existing type. The possible values that variables of this new type color_t may take are the new constant values included within braces. For example, once the color_t enumeration is declared the following expressions will be valid:
1 |
colors_t mycolor; |
Enumerations are type compatible with numeric variables, so their constants are always assigned an integer numerical value internally. If it is not specified, the integer value equivalent to the first possible value is equivalent to 0 and the following ones follow a + 1 progression. Thus, in our data type color_t that we have defined above, black would be equivalent to 0, blue would be equivalent to 1, green to 2, and so on.
We can explicity specify an integer value for any of the constant values that our enumerated type can take. If the constant value that follow it is not given an integer value, it is automatically assumed the same value as the previous one plus one. For example:
1 |
enum months_t { january=1, february, march, april, may, june, july, august, september, october, november, december} y2k; |
In this case, variable y2k of enumerated type months_t can contain any of the 12 possible values that go from january to december and that are eauivalent to values between 1 and 12(not betweent 0 and 11, since we have make january equal to 1).
Unions
Unions
allow one same portion of memory to be accessed as different data types, since
all of them are in fact the same location in memory. Its declaration and use is
similar to the one of structures but its functionality is totally different:
union union_name { |
All the
elements of the union declaration occupy the same physical space in memory. Its
size is the one of the greatest element of the declaration. For example:
1 |
union mytypes_t { |
defines
three elements:
1 |
mytypes.c |
each one
with a different data type. Since all of them are referring to the same
location in memory, the modification of one of the elements will affect the
value of all of them. We cannot store different values in them independent of
each other.