Practices
  Home arrow Practices arrow Page 6 - 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 
 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
     
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Basic Data Types and Calculations - The Assignment Operator
    (Page 6 of 14 )

    You can store the result of a calculation in a variable using the assignment operator, = . Let’s look at an example. Suppose you declare three variables with the statements

    = . Let’s look at an example. Suppose you declare three variables with the statementsYou can store the result of a calculation in a variable using the , =. Let’s look at an example. Suppose you declare three variables with the statements

    int total_fruit = 0;
    int apples = 10;
    int oranges = 6;

    You can calculate the total number of fruit with the statement

    total_fruit = apples + oranges;

    This statement will first calculate the value on the right side of the=, the sum ofapplesandoranges, and then store the result in thetotal_fruitvariable that appears on the left side of the=.

    It goes almost without saying that the expression on the right side of an assignment can be as complicated as you need. If you’ve defined variables calledboysandgirlsthat will contain the number of boys and the number of girls who are to share the fruit, you can calculate how many pieces of fruit each child will receive if you divide the total equally between them with the statement

    int fruit_per_child = 0;
    fruit_per_child = (apples + oranges) / (boys + girls);

    Note that you could equally well have declared the variablefruit_per_childand initialized it with the result of the expression directly:

    int fruit_per_child = (apples + oranges) / (boys + girls);

    You can initialize a variable with any expression, as long as all the variables involved have already been defined in preceding statements.

    Try It Out: Using the Assignment Operator

    You can package some of the code fragments from the previous section into an executable program, just to see them in action:

    // Program 2.3 – Using the assignment operator
    #include <iostream>
    using std::cout;
    using std::endl;

    int main() {
      int apples = 10;
      int oranges = 6;
      int boys = 3;
      int girls = 4;

      int fruit_per_child = (apples + oranges)/(boys + girls);

      scout << endl
            << "Each child gets "
            << fruit_per_child << " fruit.";

      cout << endl;
      return 0;
    }

    This produces the following output:


    Each child gets 2 fruit.


    This is exactly what you would expect from the preceding discussion. Multiple Assignments

    You can assign values to several variables in a single statement. For example, the following code sets the contents ofapplesandorangesto the same value:

    apples = oranges = 10;

    The assignment operator is right associative, so this statement executes by first storing the value 10 inorangesand then storing the value inorangesinapples, so it is effectively

    apples = (oranges = 10);

    This implies that the expression(oranges = 10)has a value—namely, the value stored inoranges, which is 10. This isn’t merely a curiosity. Occasions will arise in which it’s convenient to assign a value to a variable within an expression and then to use that value for some other purpose. You can write statements such as this:

    fruit = (oranges = 10) + (apples = 11);

    which will store 10 inoranges, 11 inapples, then add the two together and store the result infruit. It illustrates that an assignment expression has a value. However, although you can write statements like this, I don’t recommend it. As a rule, you should limit the number of operations per statement. Always assume that one day another programmer will want to understand and modify your code. As such, it’s your job to promote clarity and avoid ambiguity.

    Modifying the Value of a Variable

    Because the assignment operation first evaluates the right side and then stores the result in the variable on the left, you can write statements like this:

    apples = apples * 2;

    This statement calculates the value of the right side,apples * 2, using the current value ofapples, and then stores the result back in theapplesvariable. The effect of the statement is therefore to double the value contained inapples.

    The need to operate on the existing value of a variable comes up frequently—so much so, in fact, that C++ has a special form of the assignment operator to provide a shorthand way of expressing this.

    The op= Assignment Operators

    Theop=assignment operators are so called because they’re composed of an operator and an equals sign (=). Using one such operator, the previous statement for doubling the value ofapplescould be written as follows:

    apples *= 2;

    This is exactly the same operation as the statement in the last section. Theapplesvariable is multiplied by the value of the expression on the right side, and the result is stored back inapples. The right side can be any expression you like. For instance, you could write

    apples *= oranges + 2;

    This is equivalent to

    apples = apples * (oranges + 2);

    Here, the value stored inapplesis multiplied by the number oforangesplus 2, and the result is stored back inapples. (Though why you would want to multiply apples and oranges together is beyond me!)

    Theop=form of assignment also works with the addition operator, so to increase the number oforangesby 2, you could write

    oranges += 2;

    This has the same effect as the same as the statement

    oranges = oranges + 2;

    You should be able to see a pattern emerging by now. You could write the general form of an assignment statement using theop=operator aslhs op= rhs;Here,lhsis a variable andrhsis an expression. This is equivalent to the statement

    lhs = lhs op (rhs);

    The parentheses aroundrhsmean that the expressionrhsis evaluated first and the result becomes the right operand for the operationop.

    NOTE lhsis an lvalue , which is an entity to which you can assign a value. Lvalues are so called because they can appear on the left side of an assignment. The result of every expression in C++ will be either an lvalue or an rvalue .An rvalue is a result that isn’t an lvalue—that is, it can’t appear on the left of an assignment operation.

    You can use a whole range of operators in theop=form of assignment. Table 2-6 shows the complete set, including some operators you’ll meet in the next chapter.

    Table 2-6. op= Assignment Operators


    Operation      Operator   Operation             Operator
    Addition       +          Bitwise AND           &
    Subtraction    -          Bitwise OR            |
    Multiplication •          Bitwise exclusive OR  ^
    Division       /          Shift left            <<
    Modulus        %          Shift right           >>


    Note that there can be no spaces between the operator and the=. If you include a space, it will be flagged as an error.

    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 2 hosted by Hostway