|
|
|
|
|
|
Choosing a Numeric Data Type |
|
|
|
|
|
|
|
|
|
A first encounter with all the numeric data types of C++ may leave you feeling overwhelmed. To help in choosing an alternative, you may even feel tempted to toss a coin. You should resist this temptation, because each data type exists for a reason. Here are some guidelines: |
|
|
|
|
|
|
|
|
|
1. In general, int is preferable. |
|
|
|
|
 |
|
|
|
|
As a rule, you should use floating point types only when absolutely necessarythat is, when you definitely need fractional values. Not only is floating point arithmetic subject to representational errors, it also is significantly slower than integer arithmetic on most computers. |
|
|
|
|
 |
|
|
|
|
For ordinary integer data, use int instead of char or short. It's easy to make overflow errors with these smaller data types. (For character data, though, the char type is appropriate.) |
|
|
|
|
|
|
|
|
|
2. Use long only if the range of int values on your machine is too restrictive. |
|
|
|
|
 |
|
|
|
|
Compared to int, the long type requires more memory space and execution time. |
|
|
|
|
|
|
|
|
|
3. Use double and long double only if you need enormously large or small numbers, or if your machine's float values do not carry enough digits of precision. |
|
|
|
|
 |
|
|
|
|
The cost of using double and long double is increased memory space and execution time. |
|
|
|
|
|
|
|
|
|
4. Avoid the unsigned forms of integral types. |
|
|
|
|
 |
|
|
|
|
These types are primarily for manipulating bits within a memory cell, a topic this book does not cover. You might think that declaring a variable as unsigned prevents you from accidentally storing a negative number into the variable. However, the C++ compiler does not prevent you from doing so. Later in this chapter, we explain why. |
|
|
|
|
|
|
|
|
|
By following these guidelines, you'll find that the simple types you use most often are int and float, along with char for character data. Only rarely do you need the longer and shorter variations of these fundamental types. |
|
|
|
|