Home arrow C++ arrow Page 10 - More on Handling Basic Data Types
C++

More on Handling Basic Data Types


Have you ever wanted to learn how basic types of C++ variables interact in complex situations? Ivor Horton explains this, and also describes some interesting features of C++. This article is from chapter 3 of Ivor Horton's Beginning ANSC C++ The Complete Language (Apress, 2004; ISBN 1590592271).

Author Info:
By: Apress Publishing
Rating: 4 stars4 stars4 stars4 stars4 stars / 10
March 02, 2005
TABLE OF CONTENTS:
  1. · More on Handling Basic Data Types
  2. · Try It Out: Explicit Casting
  3. · Finding Out About Types
  4. · Try It Out: Finding the Sizes of Data Types
  5. · Using the Bitwise AND
  6. · Using the Bitwise Exclusive OR
  7. · Try It Out: Using the Bitwise Operators
  8. · More on Output Manipulators
  9. · Enumerated Data Types
  10. · Try It Out: Enumerated Data Types
  11. · The Lifetime of a Variable
  12. · Try It Out: The Scope Resolution Operator
  13. · Declaring External Variables

print this article
SEARCH DEVARTICLES

More on Handling Basic Data Types - Try It Out: Enumerated Data Types
(Page 10 of 13 )

Enumerations become more obviously useful when you can make decisions by comparing the value of a variable of an enumerated data type against possible enumerators. You’ll look at that in the next chapter, so here you can just work through a simple example to demonstrate some of the operations on enumerated data types you’ve seen so far:

 // Program 3.5 – Exercising an enumeration
 #include <lostream>
 using std::cout;
 int main() {
 enum Language { English, French, German, Italian,
      Spanish };
 // Display range of enumerators
 cout << "\nPossible languages are:\n"
      << English << ". English\n"
      << French  << ". French\n"
      << German  << ". German\n"
      << Italian << ". Italian\n"
      << Spanish << ". Spanish\n";
 Language tongue = German;
 cout << "\n Current language is " << tongue;
 tongue = static_cast<Language> (tongue + 1);
 cout << "\n Current language is now " << tongue
      << std::endl;
 return 0;
}

This will display the following output:

======================================================

Possible languages are:
0.  English 
1.  French 
2.  German 
3.  Italian 
4.  Spanish
Current language is 2
Current language is now 3

=====================================================

HOW IT WORKS

You first define an enumeration, Language, with this statement:

 enum Language { English, French, German, Italian,
      Spanish };

Variables of type Language can have any of the enumerators between the braces as a value. You list all the possible values with the next statement:

 cout << "\nPossible languages are:\n"
      << English << ". English\n"
      << French  << ". French\n"
      << German  << ". German\n"
      << Italian << ". Italian\n"
      << Spanish << ". Spanish\n";

An enumerator is displayed as its numeric value, so you output a text string alongside each one to show what language it corresponds to.

You declare and initialize a variable of type Language with this statement:

 Language tongue = German;

The value of this variable displays as 2, and then you give it a new value in the next statement:

 tongue = static_cast<Language>(tongue + 1);

In the expression tongue + 1, the value of tongue is converted to type int, and then 1 is added to produce the value 3 as type int. This is then converted back to type Language by the explicit cast, before it gets stored back in tongue. Without the explicit cast, the statement wouldn’t compile because there’s no automatic conversion from an integer type to an enumeration type. Of course, the value of tongue then displays as 3.


Synonyms for Data Types

You’ve seen how enumerations provide a way to define your own data types. The typedef keyword enables you to specify your own data type name as an alternative to another type name. Using typedef, you can declare the type name BigOnes as being equivalent to the standard type long with the following declaration:

 typedef long BigOnes;       // Defining BigOnes as a type
       name

Of course, this isn’t defining a new type. This just defines BigOnes as an alternative type specifier for long, so you could declare a variable mynum as type long with this statement:

 BigOnes mynum = 0;           // Declare & initialize a 
       long int variable

There’s no difference between this declaration and one using the standard built-in type name. You could equally well use this:

 long int mynum = 0;          // Declare & initialize a
       long int variable

which has exactly the same result. In fact, if you declare your own type name (such as BigOnes), you can use both type specifiers within the same program to declare different variables that will end up having the same type. However, it’s hard to come up with a justification for doing this.

Because typedef simply creates a synonym for a type that already exists, it may appear to be a bit superfluous. This isn’t at all the case. One important use for typedef is to provide flexibility in the data types used by a program that may need to be run on a variety of computers. The standard library defines the type size_t that you saw earlier in this chapter by using typedef. Let’s consider a particular instance in which you might want to use typedef.

Suppose you’re writing a program that uses several variables to record values that count events of some kind—you could be recording the number of chocolate bars produced per hour on high-speed manufacturing machinery, for instance. You know that the typical values for these counts require 4-byte integers to be used.

On some computers, type int will be 2 bytes, which is insufficient for the range of integers in the program. On other computers, type int will be 4 bytes, which is just what you want. You could resolve this by using type long, which will generally be at least 4 bytes, but on some machines it may be 8 bytes, which is wasteful—particularly if your program stores a lot of integers. You can provide the flexibility to deal with this situation by declaring your own type for use throughout the program, for example:

 typedef int Counter;      // Define the integer type for
     the program

Now you can write your program in terms of the type Counter, rather than the standard type, int. This gives you the advantage that should you want to compile your program on a machine on which the range for type int is insufficient, you can redefine Counter as

 typedef long Counter;    // Define the integer type for
     the program

Now, all the integers that are declared as Counter within the program will be of type long.

You’ll be able to do much better than this when you learn more about preprocessing directives. By using the information from the <climits> header, you can code a program so that it will automatically define your Counter type depending on the range of values available with each integer type.

You’ll see later that typedef can also fulfill a very useful role in enabling you to simplify more complex type declarations than you’ve met so far. You’ll also see later that classes provide you with a means of defining completely new data types, in which you have complete control over the properties and operations that apply to the new type.

This article is excerpted from Beginning ANSI C++ The Complete Language by Ivor Horton (Apress, 2004; ISBN  1590592271). Check it out at your favorite bookstore today. Buy this book now.


blog comments powered by Disqus
C++ ARTICLES

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- Video Memory Programming in Text Mode
- More Tricks to Gain Speed in Programming Con...
- Easy and Efficient Programming for Contests
- Preparing For Programming Contests
- Programming Contests: Why Bother?
- Polymorphism in C++
- Overview of Virtual Functions
- Inheritance in C++
- Extending the Basic Streams in C++
- Using Stringstreams in C++
- Custom Stream Manipulation in C++
- General Stream Manipulation in C++
- Serialize Your Class into Streams in C++

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials