Union, Typedef, 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
long int i_value; // Long integer version of value
float f_value; // Floating version of value
}
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
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;
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
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;
/* Now use it */
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 " <<>
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
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.
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_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:
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:
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:
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:
/* Now use it */
enum day_of_the_week today = TUESDAY;
- The general form of an enum statement is:
- 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:
- Disadvantage of using enum is that enum variables cannot be used to index an array. The following will result in an error:
// 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:
- 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.
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
Page Author
From Here You Can…
Information
- 1593 Views
- 0 Comments
Most Recent Related Content
- Lesson
- Avatar

- Title
- PHP: Simple Guestbook Tutorial
- Body
- The purpose of this tutorial is to show you how to create a very simple g...
- Author
- Lesson
- Avatar

- Title
- How to Help People Learn Without Overwhelming Them
- Body
- How Do We Promote Higher Level Thinking Today?It’s one thing for educat...
- Author
- Lesson
- Avatar

- Title
- What Is The Truth About Wikipedia?
- Body
- Author
- Lesson
- Avatar

- Title
- The Unix Shell
- Body
- IntroductionCommand-line user interfaces (CLUIs) still have a play an import...
- Author
- Lesson
- Avatar

- Title
- You Can Sell Your Expertise Online for $5,000+ Per Month
- Body
- Michael Hodosh, aka Dr. Michael, is a 49-year-old clinical psychologist who i...
- Author
- Lesson
- Avatar

- Title
- Where are you from?
- Body
- Author
- Presentation
- Avatar

- Title
- C programming (From Basics to Advanced Concepts)
- Description
- Friends, this presentation will help you to quickly revise right from the bas...
- Author
- Lesson
- Avatar

- Title
- What Works: Giving Feedback to Learners
- Body
- Like it or not, certain ways of giving learners feedback HELP them learn.Cert...
- Author
Published In…
Computer Science
Software Carpentry
Java
Agile Software Development
Everything PHP
Web 2.0
Technical Writing, Training, Publishing
Open Source
tech
Game Development
Computer Basics
PHP and MySQL
Google
J2EE
Computer Hardware
GNU & Linux
Social Media
C++
Programming Languages
Software Architecture
Computer Science Learners
singh's community
This work is public domain.