Add to Technorati Favorites
Google

Unions,Typedef, and Enums

By now, you already know what is an array, what is a structure, and how to use bit-packaged structure. Today, we will see what are unions and when & how we can use them. How you can create your own data types using typedef and how use of enums makes the code more readable and implicitly maintains integrity of data by restricting values that can be assigned to a variable of given enum type. For example, if you have defined enum days with sunday to saturday as its members starting from 0 to 6 then a value other than these cannot be assigned to a variable of days type. Let us see these advanced data types in detail.

Unions
  • A structure is used to define a data type with several fields. Each field takes up a separate storage location.
  • A union is similar to a structure; however, it defines a single location that can be given many different field names.
union value {
long int i_value; // Long integer version of value
float f_value; // Floating version of value
}


  • In a structure, the fields do not interact. Changing one field does not change any others.
  • In a union, all fields occupy the same space, so only one may be active at a time. In other words, if you put something in i_value, assigning something to f_value wipes out the old value of i_value. It is ILLEGAL to access inactive fields of a union.
  • Example of union usage
const int SHAPE_CIRCLE = 0; // Shape is a circle
const int SHAPE_RECTANGLE = 1; // Shape is a rectangle
const int SHAPE_TRIANGLE = 2; // Shape is a triangle
struct shape {
int kind; // What kind of shape is stored
union shape_union { // Union to hold shape information
struct circle circle_data; // Data for a circle
struct rectangle rectangle_data; // Data for a
rectangle
struct triangle triangle_data; // Data for a triangle
} data;
};
kind tells us which label to read.


typedef
  • C++ allows you to define your own variable types through the typedef statement.
  • This provides a way for you to extend C++'s basic types.
  • The general form of the typedef statement is:
typedef type-declaration
The type-declaration is the same as a variable declaration except a type name is used instead of a variable name.
For example:
typedef int width; defines a new type, width, that is the same as an integer. So the declaration:
width box_width;
is the same as:
int box_width;
  • At first glance, this is not much different from:
#define width int
width box_width;
However, typedefs can be used to define more complex objects which are beyond the scope of a simple #define statement, such as:
typedef int group[10];
Group is now a new type denoting an array of 10 integers. For example:
main()
{
typedef int group[10]; // Create a new type "group"
group totals; // Use the new type for a variable
// Initialize each element of total
for (i = 0; i <>
totals[i] = 0;

enum Type
  • The enumerated (enum) data type is designed for variables that can contain only a limited set of values. These values are referenced by name (tag). The compiler assigns each tag an integer value internally, such as the days of the week.

  • Cumbersome Method: Use the directive const to create values for the days of the week (day_of_the_week) as follows:
typedef int day_of_the_week; // Define the type for days of the week
const int SUNDAY = 0;
const int MONDAY = 1;
const int TUESDAY = 2;
const int WEDNESDAY = 3;
const int THURSDAY = 4;
const int FRIDAY = 5;
const int SATURDAY = 6;
/* Now to use it */
day_of_the_week today = TUESDAY;

  • Better method: Use the enum type:
enum day_of_the_week {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,FRIDAY, SATURDAY};
/* Now use it */
enum day_of_the_week today = TUESDAY;

  • The general form of an enum statement is:
enum enum-name {tag-1, tag-2, . . .} variable-name

  • Enum tags: As with structures, the enum-name or the variable-name may be omitted. The tags may be any valid C++ identifier; however, tags are usually all uppercase.

  • Additional advantage of using an enum type is that C++ will restrict the values that can be used to the ones listed in the enum declaration. The following will result in a compiler error:
today = 5; // 5 is not a day_of_the_week. Only tag assignment allowed

  • Disadvantage of using enum is that enum variables cannot be used to index an array. The following will result in an error:
enum day of the week today = TUESDAY;
// Define string versions of our days of the week
char day_names[7][] = {
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
}:
. . .
/*
* The following line generates a warning
* because today is not an integer
*/
cout << "Today is " <<>

  • To get around this problem, you need to tell C++ to treat today as an integer. This is accomplished through the cast or typecast operation. The expression int(today) tells C++, "I know today is not an integer, but treat it like one.'' To fix the above problem, use the statement:
cout << "Today is " << day_names[int(today)] << '\n';

  • Casts are also useful in expressions to make sure the variables have the correct type.
  • Old C Syntax: type (expression)
  • Problem: (float)3 + 5 --> Not clear to what float applies.
  • Solution: ((float)3) + 5 --> Clear but cumbersome

  • C++ Syntax: (type) expression --> Better Style

  • Cast is particularly useful when working with integers and floating point numbers.

  • ratio = won / lost; // Ratio will get 1.0 if ratio is float and won & lost are int.
/* The following will compute the correct ratio */
ratio = float(won) / float(lost);


This was the last part of advanced data types. Next time, we will see what functions are, how to declare and define them, and how to use them.

Source of Advanced Data Types: Oreilly's book: Practical C++ Programming by Steve Oualline

No comments: