Home arrow Practices arrow Page 7 - Basic Data Types and Calculations

Incrementing and Decrementing Integers - Practices

This article looks at some of the basic data types that are built into C++. If you're learning how to use C++, you will want to keep reading, since you'll be using these data types in all of your programs. It is taken from chapter two of the book Beginning ANSI C++: The Complete Language, by Ivor Horton (Apress, 2004; ISBN: 1590592271).

TABLE OF CONTENTS:
  1. Basic Data Types and Calculations
  2. Performing Simple Calculations
  3. Try It Out: Integer Arithmetic in Action
  4. Try It Out: Fixing the Appearance of the Output
  5. Try It Out: Using Integer Variables
  6. The Assignment Operator
  7. Incrementing and Decrementing Integers
  8. Numerical Functions for Integers
  9. Floating-Point Operations
  10. Try It Out: Floating-Point Arithmetic
  11. Try It Out: Yet More Output Manipulators
  12. Working with Characters
  13. Functional Notation for Initial Values
  14. Exercises
By: Apress Publishing
Rating: starstarstarstarstar / 14
September 08, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Youíve seen how you can modify a variable using the assignment operator and how you can increment one with the += operator. Iím sure youíve also deduced that you can decrement a variable with-=. However, there are two other rather unusual arithmetic operators that can perform the same tasks. Theyíre called the increment and decrement operators,++and--respectively.

+= operator. Iím sure youíve also deduced that you can decrement a variable with -= . However, there are two other rather unusual arithmetic operators that can perform the same tasks. Theyíre called the and , ++ and -- respectively.Youíve seen how you can modify a variable using the assignment operator and how you can increment one with the += operator. Iím sure youíve also deduced that you can decrement a variable with -=. However, there are two other rather unusual arithmetic operators that can perform the same tasks. Theyíre called the and , ++ and --respectively.

These operators are more than just other options, and youíll find them to be quite an asset once you get further into applying C++ in earnest. The increment and decrement operators are unary operators that can be applied to an integer variable. For example, assuming the variables are of typeint, the following three statements all have exactly the same effect:

count = count + 1; count += 1; ++count;

The preceding statements each increment the variablecountby 1. The last form, using the increment operator, is clearly the most concise. The action of this operator is different from the other operators that youíve seen, in that it directly modifies the value of its operand. The effect in an expression is to increment the value of the variable and then to use that incremented value in the expression. For example, supposecounthas the value 5, and you execute this statement:

total = ++count + 6;

The increment and decrement operators are of higher precedence than all the binary arithmetic operators. Thus,countwill be first incremented to the value 6, and then this value will be used in the evaluation of the expression on the right side of the assignment operation. The variabletotalwill therefore be assigned the value 12.

You use the decrement operator in the same way as the increment operator:

total = --count + 6;

Assumingcountis 6 before executing this statement, the decrement operator will reduce it to 5, and this value will be used to calculate the value to be stored intotal, which will be 11.

Postfix Increment and Decrement Operations

So far, youíve written the operators in front of the variables to which they apply. This is called the prefix form. The operators can also be written after the variables to which they apply; this is the postfix form, and the effect is slightly different. When you use the postfix form of++, the variable to which it applies is incremented after its value is used in context. For example, you can rewrite the earlier example as follows:

total = count++ + 6;

With the same initial value of 5 forcount,totalis assigned the value 11, because the initial value ofcountis used to evaluate the expression before the increment by 1 is applied. The variablecountwill then be incremented to 6. The preceding statement is equivalent to the following two statements:

total = count + 6; ++count;

In an expression such asa++ + b, or evena+++b, itís less than obvious what is meant, or indeed what the compiler will do. These two expressions are actually the same, but in the second case you might really have meanta + ++b, which has a different meaningóit evaluates to one more than the other two expressions. It would be clearer to write the preceding statement as follows:

total = 6 + count++;

Alternatively, you can use parentheses:

total = (count++) + 6;

The rules that Iíve discussed in relation to the increment operator also apply to the decrement operator. For example, supposecounthas the initial value 5, and you write the statement

total = --count + 6;

This results intotalhaving the value 10 assigned, whereas if you write the statement

total = 6 + count-- ;

the value oftotalis set to 11.

You should avoid using the prefix form of these operators to operate on a variable more than once in an expression. Suppose the variablecounthas the value 5, and you write

total = ++count * 3 + ++count * 5;

First, it looks rather untidy, but thatís the least of the problems with this. Second, and crucially, the statement modifies the value of a variable more than once and the result is undefined in C++. You could and should get an error message from the compiler with this statement, but in some instances you wonít. This isnít a desirable feature in a program to say the least, so donít modify a variable more than once in a statement.

Note also that the effects of statements such as the following are undefined:

k = ++k + 1;

Here youíre incrementing the value of the variable that appears on the right of the assignment operator, so youíre attempting to modify the value of the variablektwice within one expression. Each variable can be modified only once as a result of evaluating a single expression, and the prior value of the variable may only be accessed to determine the value to be stored. Although such expressions are undefined according to the C++ standard, this doesnít mean that your compiler wonít compile them. It just means that there is no guarantee of consistency in the results.

The increment and decrement operators are usually applied to integers, particularly in the context of loops, as youíll see in Chapter 5, and youíll see later in this chapter that they can be applied to floating-point values too. In later chapters, youíll explore how they can also be applied to certain other data types in C++, in some cases with rather specialized (but very useful) effects.

The const Keyword

Youíll often feel the need to use constants of one kind or another in your programs: the number of days in January, perhaps, or p, the ratio of the circumference of a circle to its diameter, or even the number of buns in a bakerís dozen. However, you should avoid using numeric literals explicitly within calculations; itís much better to use a variable that youíve initialized to the appropriate value instead. For example, multiplying a value by 3 doesnít necessarily communicate that youíre converting from yards to feet, but multiplying by a variable with the name feet_per_yard that youíve initialized to the value 3 makes it absolutely clear what youíre doing. Explicit numeric literals in a program are sometimes referred to as magic numbers, particularly when their purpose and origin is less than obvious.

that youíve initialized to the value 3 makes it absolutely clear what youíre doing. Explicit numeric literals in a program are sometimes referred to as , particularly when their purpose and origin is less than obvious.feet_per_yard that youíve initialized to the value 3 makes it absolutely clear what youíre doing. Explicit numeric literals in a program are sometimes referred to as , particularly when their purpose and origin is less than obvious.Youíll often feel the need to use constants of one kind or another in your programs: the number of days in January, perhaps, or p, the ratio of the circumference of a circle to its diameter, or even the number of buns in a bakerís dozen. However, you should avoid using numeric literals explicitly within calculations; itís much better to use a variable that youíve initialized to the appropriate value instead. For example, multiplying a value by 3 doesnít necessarily communicate that youíre converting from yards to feet, but multiplying by a variable with the name feet_per_yard that youíve initialized to the value 3 makes it absolutely clear what youíre doing. Explicit numeric literals in a program are sometimes referred to as , particularly when their purpose and origin is less than obvious.

Another good reason for using a variable instead of a magic number is that you reduce the number of maintenance points in your code. Imagine that your magic number represents something that changes from time to timeóan interest rate, for instanceóand that it crops up on several occasions in your code. When the rate changes, you could be faced with a sizable task to correct your program. If youíve defined a variable for the purpose, you only need to change the value once, at the point of initialization.

Of course, if you use a variable to hold a constant of this kind, you really want to nail the value down and protect it from accidental modifications. You can use the keywordconstto do this, for example:

const int feet_per_yard = 3; // Conversion factor yards to feet

You can declare any kind of ďvariableĒ asconst. The compiler will check that you donít attempt to alter the value of such a variable. For example, if you put somethingconston the left of an assignment operator, it will be flagged as an error. The obvious consequence of this is that you must always supply an initial value for a variable that you declare asconst.

Be aware that declaring a variable asconstalters its type. A variable of typeconst intis quite different from a variable of typeint.

Try It Out: Using const

You could implement a little program to convert a length entered as yards, feet, and inches into inches:

// Program 2.4 - Using const
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

int main() {
  const int inches_per_foot = 12;
  const int feet_per_yard = 3;
  int yards = 0;
  int feet = 0;
  int inches = 0;

  // Read the length from the keyboard
  cout << "Enter a length as yards, feet, and inches: ";
  cin >> yards >> feet >> inches;

  // Output the length in inches
  cout << endl
       << "Length in inches is "
       << inches + inches_per_foot * (feet + feet_per_yard * yards)
       << endl;
  return 0;
}

A typical result from this program is the following:


Enter a length as yards, feet, and inches: 2 2 11
Length in inches is 107

HOW IT WORKS

Thereís an extrausingstatement compared to previous examples:

using std::cin;

This introduces the namecinfrom thestdnamespace into the program file that refers to the standard input streamóthe keyboard.

You have two conversion constants defined by the statements

const int inches_per_foot = 12;
const int feet_per_yard = 3;

Declaring them with the keywordconstwill prevent direct modification of these variables. You could test this by adding a statement such as

inches_per_foot = 15;

With a statement like this after the declaration of the constant, the program would no longer compile.

You prompt for input and read the values foryards,feet, andincheswith these statements:

cout << "Enter a length as yards, feet, and inches: ";
cin >> yards >> feet >> inches;

Notice how the second line specifies several successive input operations from the stream,cin.You do this by using the extraction operator,>>, that I mentioned briefly in the last chapter. Itís analogous to usingcout, the stream output operation, for multiple values. The appearance of the insertion and extraction operators provides you with a visual cue as to the direction in which data flows.

The first value read from the keyboard will be stored inyards, the second infeet, and the third ininches. The input handling here is very flexible: you can enter all three values on one line, separated by spaces (in fact, by any whitespace characters), or you can enter them on several lines.

You perform the conversion to inches within the output statement itself:

cout << endl
     << "Length in inches is "
     << inches + inches_per_foot * (feet + feet_per_yard * yards)
     << endl;

As you can see, the fact that your conversion factors were declared asconstin no way affects their use in expressions, just as long as you donít try to modify them.



 
 
>>> More Practices Articles          >>> More By Apress Publishing
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PRACTICES ARTICLES

- Calculating Development Project Costs
- More Techniques for Finding Things
- Finding Things
- Finishing the System`s Outlines
- The System in So Many Words
- Basic Data Types and Calculations
- What`s the Address? Pointers
- Design with ArgoUML
- Pragmatic Guidelines: Diagrams That Work
- Five-Step UML: OOAD for Short Attention Span...
- Five-Step UML: OOAD for Short Attention Span...
- Introducing UML: Object-Oriented Analysis an...
- Class and Object Diagrams
- Class Relationships
- Classes

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: