Practices
  Home arrow Practices arrow Page 7 - Basic Data Types and Calculations
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
IBM Rational Software Development Conference
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PRACTICES

Basic Data Types and Calculations
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 12
    2005-09-08

    Table of Contents:
  • Basic Data Types and Calculations
  • Performing Simple Calculations
  • Try It Out: Integer Arithmetic in Action
  • Try It Out: Fixing the Appearance of the Output
  • Try It Out: Using Integer Variables
  • The Assignment Operator
  • Incrementing and Decrementing Integers
  • Numerical Functions for Integers
  • Floating-Point Operations
  • Try It Out: Floating-Point Arithmetic
  • Try It Out: Yet More Output Manipulators
  • Working with Characters
  • Functional Notation for Initial Values
  • Exercises

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    The Best Selling PC Migration Utility.
     
    ADVERTISEMENT

    Route your faxes to your email inbox. Private, secure fax numbers available from CallWave. Choose your fax number.

    Basic Data Types and Calculations - Incrementing and Decrementing Integers
    (Page 7 of 14 )

    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


     

    Buy this book now. This article was taken from chapter two of the book 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.

       

    PRACTICES ARTICLES

    - 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
    - Basic Ideas
    - Choosing the Right Team
    - Trees
    - Basic Array Searching in C++

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway