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

The Assignment Operator - 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).

  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



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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- 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: