C++ Primer: Dealing with Data
- Dec 30, 2004
- Simple Variables
- The const Qualifier
- Floating-Point Numbers
- C++ Arithmetic Operators
- Summary
- Review Questions
- Programming Exercises
C++ Arithmetic Operators
Perhaps you have warm memories of doing arithmetic drills in grade school. You can give that same pleasure to your computer. C++ uses operators to do arithmetic. It provides operators for five basic arithmetic calculations: addition, subtraction, multiplication, division, and taking the modulus. Each of these operators uses two values (called operands) to calculate a final answer. Together, the operator and its operands constitute an expression. For example, consider the following statement:
int wheels = 4 + 2;
The values 4 and 2 are operands, the + symbol is the addition operator, and 4 + 2 is an expression whose value is 6.
Here are C++'s five basic arithmetic operators:
The + operator adds its operands. For example, 4 + 20 evaluates to 24.
The - operator subtracts the second operand from the first. For example, 12 - 3 evaluates to 9.
The * operator multiplies its operands. For example, 28 * 4 evaluates to 112.
The / operator divides its first operand by the second. For example, 1000 / 5 evaluates to 200. If both operands are integers, the result is the integer portion of the quotient. For example, 17 / 3 is 5, with the fractional part discarded.
The % operator finds the modulus of its first operand with respect to the second. That is, it produces the remainder of dividing the first by the second. For example, 19 % 6 is 1 because 6 goes into 19 three times, with a remainder of 1. Both operands must be integer types; using the % operator with floating-point values causes a compile-time error. If one of the operands is negative, the sign of the result depends on the implementation.
Of course, you can use variables as well as constants for operands. Listing 3.10 does just that. Because the % operator works only with integers, we'll leave it for a later example.
Listing 3.10 arith.cpp
// arith.cpp -- some C++ arithmetic #include <iostream> int main() { using namespace std; float hats, heads; cout.setf(ios_base::fixed, ios_base::floatfield); // fixed-point cout << "Enter a number: "; cin >> hats; cout << "Enter another number: "; cin >> heads; cout << "hats = " << hats << "; heads = " << heads << endl; cout << "hats + heads = " << hats + heads << endl; cout << "hats - heads = " << hats - heads << endl; cout << "hats * heads = " << hats * heads << endl; cout << "hats / heads = " << hats / heads << endl; return 0; }
Compatibility Note
If your compiler does not accept the ios_base forms in setf(), try using the older ios forms instead; that is, substitute ios::fixed for ios_base::fixed, etc.
As you can see in the following sample output from the program in Listing 3.10, you can trust C++ to do simple arithmetic:
Enter a number: 50.25 Enter another number: 11.17 hats = 50.250000; heads = 11.170000 hats + heads = 61.419998 hats - heads = 39.080002 hats * heads = 561.292480 hats / heads = 4.498657
Well, maybe you can't trust it completely. Adding 11.17 to 50.25 should yield 61.42, but the output reports 61.419998. This is not an arithmetic problem; it's a problem with the limited capacity of type float to represent significant figures. Remember, C++ guarantees just six significant figures for float. If you round 61.419998 to six figures, you get 61.4200, which is the correct value to the guaranteed precision. The moral is that if you need greater accuracy, you should use double or long double.
Order of Operation: Operator Precedence and Associativity
Can you trust C++ to do complicated arithmetic? Yes, but you must know the rules C++ uses. For example, many expressions involve more than one operator. That can raise questions about which operator gets applied first. For example, consider this statement:
int flyingpigs = 3 + 4 * 5; // 35 or 23?
The 4 appears to be an operand for both the + and * operators. When more than one operator can be applied to the same operand, C++ uses precedence rules to decide which operator is used first. The arithmetic operators follow the usual algebraic precedence, with multiplication, division, and the taking of the modulus done before addition and subtraction. Thus 3 + 4 * 5 means 3 + (4 * 5), not (3 + 4) * 5. So the answer is 23, not 35. Of course, you can use parentheses to enforce your own priorities. Appendix D, "Operator Precedence," shows precedence for all the C++ operators. Note that *, /, and % are all in the same row in Appendix D. That means they have equal precedence. Similarly, addition and subtraction share a lower precedence.
Sometimes the precedence list is not enough. Consider the following statement:
float logs = 120 / 4 * 5; // 150 or 6?
Once again, 4 is an operand for two operators. But the / and * operators have the same precedence, so precedence alone doesn't tell the program whether to first divide 120 by 4 or multiply 4 by 5. Because the first choice leads to a result of 150 and the second to a result of 6, the choice is an important one. When two operators have the same precedence, C++ looks at whether the operators have a left-to-right associativity or a right-to-left associativity. Left-to-right associativity means that if two operators acting on the same operand have the same precedence, you apply the left-hand operator first. For right-to-left associativity, you apply the right-hand operator first. The associativity information, too, is in Appendix D. Appendix D shows that multiplication and division associate left-to-right. That means you use 4 with the leftmost operator first. That is, you divide 120 by 4, get 30 as a result, and then multiply the result by 5 to get 150.
Note that the precedence and associativity rules come into play only when two operators share the same operand. Consider the following expression:
int dues = 20 * 5 + 24 * 6;
Operator precedence tells you two things: The program must evaluate 20 * 5 before doing addition, and the program must evaluate 24 * 6 before doing addition. But neither precedence nor associativity says which multiplication takes place first. You might think that associativity says to do the leftmost multiplication first, but in this case, the two * operators do not share a common operand, so the rules don't apply. In fact, C++ leaves it to the implementation to decide which order works best on a system. For this example, either order gives the same result, but there are circumstances in which the order can make a difference. You'll see one in Chapter 5, which discusses the increment operator.
Division Diversions
You have yet to see the rest of the story about the division operator (/). The behavior of this operator depends on the type of the operands. If both operands are integers, C++ performs integer division. That means any fractional part of the answer is discarded, making the result an integer. If one or both operands are floating-point values, the fractional part is kept, making the result floating-point. Listing 3.11 illustrates how C++ division works with different types of values. As in Listing 3.10, Listing 3.11 invokes the setf() member function to modify how the results are displayed.
Listing 3.11 divide.cpp
// divide.cpp -- integer and floating-point division #include <iostream> int main() { using namespace std; cout.setf(ios_base::fixed, ios_base::floatfield); cout << "Integer division: 9/5 = " << 9 / 5 << endl; cout << "Floating-point division: 9.0/5.0 = "; cout << 9.0 / 5.0 << endl; cout << "Mixed division: 9.0/5 = " << 9.0 / 5 << endl; cout << "double constants: 1e7/9.0 = "; cout << 1.e7 / 9.0 << endl; cout << "float constants: 1e7f/9.0f = "; cout << 1.e7f / 9.0f << endl; return 0; }
Compatibility Note
If your compiler does not accept the ios_base forms in setf(), try using the older ios forms instead.
Some C++ implementations based on pre-ANSI C compilers don't support the f suffix for floating-point constants. If you find yourself facing this problem, you can replace 1.e7f / 9.0f with (float) 1.e7 /(float) 9.0.
Some implementations suppress trailing zeros.
Here is the output from the program in Listing 3.11 for one implementation:
Integer division: 9/5 = 1 Floating-point division: 9.0/5.0 = 1.800000 Mixed division: 9.0/5 = 1.800000 double constants: 1e7/9.0 = 1111111.111111 float constants: 1e7f/9.0f = 1111111.125000
The first output line shows that dividing the integer 9 by the integer 5 yields the integer 1. The fractional part of 4 / 5 (or 0.8) is discarded. (You'll see a practical use for this kind of division when you learn about the modulus operator, later in this chapter.) The next two lines show that when at least one of the operands is floating-point, you get a floating-point answer of 1.8. Actually, when you try to combine mixed types, C++ converts all the concerned types to the same type. You'll learn about these automatic conversions later in this chapter. The relative precisions of the last two lines show that the result is type double if both operands are double and that it is float if both operands are float. Remember, floating-point constants are type double by default.
A Glimpse at Operator Overloading
In Listing 3.11, the division operator represents three distinct operations: int division, float division, and double division. C++ uses the context—in this case the type of operands—to determine which operator is meant. The process of using the same symbol for more than one operation is called operator overloading. C++ has a few examples of overloading built in to the language. C++ also lets you extend operator overloading to user-defined classes, so what you see here is a precursor of an important OOP property. (See Figure 3.4.)
Figure 3.4 Different divisions.
The Modulus Operator
Most people are more familiar with addition, subtraction, multiplication, and division than with the modulus operation, so let's take a moment to look at the modulus operator in action. The modulus operator returns the remainder of an integer division. In combination with integer division, the modulus operation is particularly useful in problems that require dividing a quantity into different integral units, such as converting inches to feet and inches or converting dollars to quarters, dimes, nickels, and pennies. In Chapter 2, Listing 2.6 converts weight in British stone to pounds. Listing 3.12 reverses the process, converting weight in pounds to stone. A stone, you remember, is 14 pounds, and most British bathroom scales are calibrated in this unit. The program uses integer division to find the largest number of whole stone in the weight, and it uses the modulus operator to find the number of pounds left over.
Listing 3.12 modulus.cpp
// modulus.cpp -- uses % operator to convert lbs to stone #include <iostream> int main() { using namespace std; const int Lbs_per_stn = 14; int lbs; cout << "Enter your weight in pounds: "; cin >> lbs; int stone = lbs / Lbs_per_stn; // whole stone int pounds = lbs % Lbs_per_stn; // remainder in pounds cout << lbs << " pounds are " << stone << " stone, " << pounds << " pound(s).\n"; return 0; }
Here is a sample run of the program in Listing 3.12:
Enter your weight in pounds: 177 184 pounds are 12 stone, 9 pound(s).
In the expression lbs / Lbs_per_stn, both operands are type int, so the computer performs integer division. With a lbs value of 177, the expression evaluates to 12. The product of 12 and 14 is 168, so the remainder of dividing 14 into 177 is 9, and that's the value of lbs % Lbs_per_stn. Now you are prepared technically, if not emotionally, to respond to questions about your weight when you travel in Great Britain.
Type Conversions
C++'s profusion of types lets you match the type to the need. It also complicates life for the computer. For example, adding two short values may involve different hardware instructions than adding two long values. With 11 integral types and 3 floating-point types, the computer can have a lot of different cases to handle, especially if you start mixing types. To help deal with this potential mishmash, C++ makes many type conversions automatically:
C++ converts values when you assign a value of one arithmetic type to a variable of another arithmetic type.
C++ converts values when you combine mixed types in expressions.
C++ converts values when you pass arguments to functions.
If you don't understand what happens in these automatic conversions, you might find some program results baffling, so let's take a more detailed look at the rules.
Conversion on Assignment
C++ is fairly liberal in allowing you to assign a numeric value of one type to a variable of another type. Whenever you do so, the value is converted to the type of the receiving variable. For example, suppose so_long is type long, thirty is type short, and you have the following statement in a program:
so_long = thirty; // assigning a short to a long
The program takes the value of thirty (typically a 16-bit value) and expands it to a long value (typically a 32-bit value) upon making the assignment. Note that the expansion creates a new value to place into so_long; the contents of thirty are unaltered.
Assigning a value to a type with a greater range usually poses no problem. For example, assigning a short value to a long variable doesn't change the value; it just gives the value a few more bytes in which to laze about. However, assigning a large long value such as 2111222333 to a float variable results in the loss of some precision. Because float can have just six significant figures, the value can be rounded to 2.11122E9. So, while some conversions are safe, some may pose difficulties. Table 3.3 points out some possible conversion problems.
Table 3.3 Potential Numeric Conversion Problems
Conversion Type |
Potential Problems |
Bigger floating-point type to smaller floating-point type, such as double to float |
Loss of precision (significant figures); value might be out of range for target type, in which case result is undefined |
Floating-point type to integer type |
Loss of fractional part; original value might be out of range for target type, in which case result is undefined |
Bigger integer type to smaller integer type, such as long to short |
Original value might be out of range for target type; typically just the low-order bytes are copied |
A zero value assigned to a bool variable is converted to false, and a nonzero value is converted to true.
Assigning floating-point values to integer types poses a couple problems. First, converting floating-point to integer results in truncating the number (discarding the fractional part). Second, a float value might be too big to fit in a cramped int variable. In that case, C++ doesn't define what the result should be; that means different implementations can respond differently. Listing 3.13 shows a few conversions by assignment.
Listing 3.13 assign.cpp
// assign.cpp -- type changes on assignment #include <iostream> int main() { using namespace std; cout.setf(ios_base::fixed, ios_base::floatfield); float tree = 3; // int converted to float int guess = 3.9832; // float converted to int int debt = 7.2E12; // result not defined in C++ cout << "tree = " << tree << endl; cout << "guess = " << guess << endl; cout << "debt = " << debt << endl; return 0; }
Here is the output from the program in Listing 3.13 for one system:
tree = 3.000000 guess = 3 debt = 1634811904
In this case, tree is assigned the floating-point value 3.0. Assigning 3.9832 to the int variable guess causes the value to be truncated to 3; C++ uses truncation (discarding the fractional part) and not rounding (finding the closest integer value) when converting floating-point types to integer types. Finally, note that the int variable debt is unable to hold the value 7.2E12. This creates a situation in which C++ doesn't define the result. On this system, debt ends up with the value 1634811904, or about 1.6E09. Well, that's a novel way to reduce massive indebtedness!
Some compilers warn you of possible data loss for those statements that initialize integer variables to floating-point values. Also, the value displayed for debt varies from compiler to compiler. For example, running the same program from Listing 3.13 on a second system produced a value of 2147483647.
Conversions in Expressions
Consider what happens when you combine two different arithmetic types in one expression. C++ makes two kinds of automatic conversions in that case. First, some types are automatically converted whenever they occur. Second, some types are converted when they are combined with other types in an expression.
First, let's examine the automatic conversions. When it evaluates expressions, C++ converts bool, char, unsigned char, signed char, and short values to int. In particular, true is promoted to 1 and false to 0. These conversions are termed integral promotions. For example, consider the following fowl statements:
short chickens = 20; // line 1 short ducks = 35; // line 2 short fowl = chickens + ducks; // line 3
To execute the statement on line 3, a C++ program takes the values of chickens and ducks and converts both to int. Then, the program converts the result back to type short because the answer is assigned to a type short variable. You might find this a bit roundabout, but it does make sense. The int type is generally chosen to be the computer's most natural type, which means the computer probably does calculations fastest for that type.
There's some more integral promotion: The unsigned short type is converted to int if short is smaller than int. If the two types are the same size, unsigned short is converted to unsigned int. This rule ensures that there's no data loss in promoting unsigned short. Similarly, wchar_t is promoted to the first of the following types that is wide enough to accommodate its range: int, unsigned int, long, or unsigned long.
Then there are the conversions that take place when you arithmetically combine different types, such as adding an int to a float. When an operation involves two types, the smaller is converted to the larger. For example, the program in Listing 3.11 divides 9.0 by 5. Because 9.0 is type double, the program converts 5 to type double before it does the division. More generally, the compiler goes through a checklist to determine which conversions to make in an arithmetic expression. Here's the list, which the compiler goes through in order:
If either operand is type long double, the other operand is converted to long double.
Otherwise, if either operand is double, the other operand is converted to double.
Otherwise, if either operand is float, the other operand is converted to float.
Otherwise, the operands are integer types and the integral promotions are made.
In that case, if either operand is unsigned long, the other operand is converted to unsigned long.
Otherwise, if one operand is long int and the other is unsigned int, the conversion depends on the relative sizes of the two types. If long can represent possible unsigned int values, unsigned int is converted to long.
Otherwise, both operands are converted to unsigned long.
Otherwise, if either operand is long, the other is converted to long.
Otherwise, if either operand is unsigned int, the other is converted to unsigned int.
If the compiler reaches this point in the list, both operands should be int.
ANSI C follows the same rules as C++, but classic K&R C has slightly different rules. For example, classic C always promotes float to double, even if both operands are float.
Conversions in Passing Arguments
Normally, C++ function prototyping controls type conversions for the passing of arguments, as you'll learn in Chapter 7, "Functions: C++'s Programming Modules." However, it is possible, although usually unwise, to waive prototype control for argument passing. In that case, C++ applies the integral promotions to the char and short types (signed and unsigned). Also, to preserve compatibility with huge amounts of code in classic C, C++ promotes float arguments to double when passing them to a function that waives prototyping.
Type Casts
C++ empowers you to force type conversions explicitly via the type cast mechanism. (C++ recognizes the need for type rules, and it also recognizes the need to occasionally override those rules.) The type cast comes in two forms. For example, to convert an int value stored in a variable called thorn to type long, you can use either of the following expressions:
(long) thorn // returns a type long conversion of thorn long (thorn) // returns a type long conversion of thorn
The type cast doesn't alter the thorn variable itself; instead, it creates a new value of the indicated type, which you can then use in an expression, as in the following:
cout << int('Q'); // displays the integer code for 'Q'
More generally, you can do the following:
(typeName) value // converts value to typeName type typeName (value) // converts value to typeName type
The first form is straight C. The second form is pure C++. The idea behind the new form is to make a type cast look like a function call. This makes type casts for the built-in types look like the type conversions you can design for user-defined classes.
C++ also introduces four type cast operators that are more restrictive in how they can be used. Chapter 15, "Friends, Exceptions, and More," covers them. Of the four, the static_cast<> operator, can be used for converting values from one numeric type to another. For example, using it to convert thorn to a type long value looks like this:
static_cast<long> (thorn) // returns a type long conversion of thorn
More generally, you can do the following:
static_cast<typeName> (value) // converts value to typeName type
As Chapter 15 discusses further, Stroustrup felt that the traditional C-style type cast is dangerously unlimited in its possibilities.
Listing 3.14 briefly illustrates both forms. Imagine that the first section of this listing is part of a powerful ecological modeling program that does floating-point calculations that are converted to integral numbers of birds and animals. The results you get depend on when you convert. The calculation for auks first adds the floating-point values and then converts the sum to int upon assignment. But the calculations for bats and coots first use type casts to convert the floating-point values to int and then sum the values. The final part of the program shows how you can use a type cast to display the ASCII code for a type char value.
Listing 3.14 typecast.cpp
// typecast.cpp -- forcing type changes #include <iostream> int main() { using namespace std; int auks, bats, coots; // the following statement adds the values as double, // then converts the result to int auks = 19.99 + 11.99; // these statements add values as int bats = (int) 19.99 + (int) 11.99; // old C syntax coots = int (19.99) + int (11.99); // new C++ syntax cout << "auks = " << auks << ", bats = " << bats; cout << ", coots = " << coots << endl; char ch = 'Z'; cout << "The code for " << ch << " is "; // print as char cout << int(ch) << endl; // print as int return 0; }
Here is the result of the program in Listing 3.14:
auks = 31, bats = 30, coots = 30 The code for Z is 90
First, adding 19.99 to 11.99 yields 31.98. When this value is assigned to the int variable auks, it's truncated to 31. But using type casts truncates the same two values to 19 and 11 before addition, making 30 the result for both bats and coots. The final cout statement uses a type cast to convert a type char value to int before it displays the result. This causes cout to print the value as an integer rather than as a character.
This program illustrates two reasons to use type casting. First, you might have values that are stored as type double but are used to calculate a type int value. For example, you might be fitting a position to a grid or modeling integer values, such as populations, with floating-point numbers. You might want the calculations to treat the values as int. Type casting enables you to do so directly. Notice that you get a different result, at least for these values, when you convert to int and add than you do when you add first and then convert to int.
The second part of the program shows the most common reason to use a type cast: the capability to compel data in one form to meet a different expectation. In Listing 3.14, for example, the char variable ch holds the code for the letter Z. Using cout with ch displays the character Z because cout zeros in on the fact that ch is type char. But by type casting ch to type int, you get cout to shift to int mode and print the ASCII code stored in ch.