Practices
  Home arrow Practices arrow Page 6 - Basic Data Types and Calculations
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
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? 
Google.com  
PRACTICES

Basic Data Types and Calculations
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 13
    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:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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


    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 statements You 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 of apples and oranges , and then store the result in the total_fruit variable 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 called boys and girls that 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 variable fruit_per_child and 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 fol lowing code sets the contents of apples and oranges to the same value:

    apples = oranges = 10;

    The assignment operator is right associative, so this statement executes by first storing the value 10 in oranges and then storing the value in oranges in apples , so it is effectively

    apples = (oranges = 10);

    This implies that the expression (oranges = 10) has a value—namely, the value stored in oranges , 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 in oranges , 11 in apples , then add the two together and store the result in fruit . 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 of apples , and then stores the result back in the apples variable. The effect of the statement is therefore to double the value contained in apples .

    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

    The op= 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 of apples could be written as follows:

    apples *= 2;

    This is exactly the same operation as the statement in the last section. The apples variable is multiplied by the value of the expression on the right side, and the result is stored back in apples . 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 in apples is multiplied by the number of oranges plus 2, and the result is stored back in apples . (Though why you would want to multiply apples and oranges together is beyond me!)

    The op= form of assignment also works with the addition operator, so to increase the number of oranges by 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 the op= operator as lhs op= rhs; Here, lhs is a variable and rhs is an expression. This is equivalent to the statement

    lhs = lhs op (rhs) ;

    The parentheses around rhs mean that the expression rhs is evaluated first and th e result becomes the right operand for the operation op.

    NOTE lhs is 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 the op= 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
     

       

    PRACTICES ARTICLES

    - 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
    - Basic Ideas





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek