Chapter 4

Integer Expressions

In This Chapter

arrow Declaring variables

arrow Creating expressions

arrow Unraveling compound expressions

arrow Analyzing the assignment operator

arrow Incrementing variables with the unary operator

In this chapter, get familiar with integer declarations and expressions. Ah, memories of algebra class. With any luck, it introduced you to the concepts of variables and expressions. The teacher would write something on the board like

  x = 1

This equation defines a variable x and sets it equal to the value 1 until some subsequent statement changes that relationship for some reason. The term x becomes a replacement for 1. The teacher would then write the following expression:

  y = 2x

Because I know that x is 1, I now know that y is equal to 2. This was a real breakthrough in the seventh grade. The good news is that all conventional computer languages follow this same pattern of creating and manipulating variables.

Declaring Variables

An integer variable declaration starts with the keyword int followed by the name of a variable and a semicolon, as in the following example:

  int n1;       // declare a variable n1

All variables in C++ must be declared before they can be used. A variable declaration reserves a small amount of space in memory, just enough for a single integer (in this case), and assigns it a name. You can declare more than one variable in the same declaration, as in the following example, but it’s not a good idea; the reasons become clear as you work through subsequent chapters:

  int n2, n3;   // declare two variables n2 and n3

remember.eps A keyword is a word that has meaning to C++. You cannot give a variable a name that’s the same as a keyword. Thus, for example, you can’t create a variable with the name int. However, keywords are case-sensitive, so you could create a variable Int or INT. Later chapters introduce you a lot more keywords.

The fact that the keyword int is used instead of integer is just a reflection of the overall terseness of the C++ language. Makes you wonder whether the creators of the language were poor typists and wanted to minimize the amount of typing they had to do.

warning.eps If you exceed the range of an int, you’ll get the wrong answer. Unlike in algebra class, the range of an integer is not unlimited in C++. However, it is very large indeed. I discuss variable size and range in Chapter 14.

Variable names

You can name a variable anything you like — with the following restrictions:

  • The first letter of the variable must be a character in the sequence a through z, A through Z, or underscore (_).
  • Every letter after the first must be a character in the sequence a through z, A through Z, underscore (_), or the digits 0 through 9.
  • A variable name can be of any length. All characters are significant.

The following are legal variable names:

  int myVariable;
int MyVariable;
int myNumber2Variable;
int _myVariable;
int my_Variable;

The following are not legal variable names:

  int myPercentage%;      // contains illegal character
int 2ndVariable;        // starts with a digit
int my Variable;        // contains a space

Variable names should be descriptive. Variable names such as x are discouraged.

Assigning a value to a variable

Every variable has a value from the moment it’s declared. However, until you assign it a value, a variable will just assume whatever garbage value happens to be in that memory location when it’s allocated. So, if you don’t assign a value, you don’t know what value is lurking in that variable — and it’s likely to change every time you run the program.

You can assign a variable a value by using the equals sign, as in the following example:

  int n;        // declare a variable n
n = 1;        // set it to 1

This looks remarkably similar to the assignment statement in algebra class, but the effect is not quite the same. In C++, the assignment statement says, “Take the value on the right-hand side of the equals sign (in this case, 1) and store it in the location on the left-hand side, overwriting whatever was there before (in this case, n).”

You can see the difference in the following expression:

  n = n + 1;    // increment the variable n

This statement would make absolutely no sense in algebra class. How could n be both equal to n and n + 1 at the same time? However, this statement makes perfect sense in C++ if you follow the definition for assignment just given: “Take the value stored in the variable n (1) ,add 1, and store the result (2) in the variable n.” This is shown graphically in Figure 4-1.

9781118823873-fg0401.tif

Figure 4-1: The effect of executing the expression n = n + 1 when n starts out as 1.

Initializing a variable at declaration

You can initialize your variable at the time it’s declared by following it with an equals sign and a value:

  int n = 1;    // declare and initialize variable

warning.eps This statement initializes only the one variable, so if you write the following compound declaration

  int n1, n2 = 0;

you’ve initialized n2 but not n1. This is one reason it’s not a good idea to declare multiple variables in a single declaration. (See the sidebar “Forgetting to initialize a variable” for a few more gruesome details.)

Integer Constants

C++ understands any symbol that begins with a digit and contains only digits to be an integer constant. The following are legal constants:

  123
1
256

A constant cannot contain any funny characters. The following is not legal:

  123Z456

The following is legal but doesn’t mean what you may think:

  123+456

This actually defines the sum of two constants 123 and 456, or the value 579.

technicalstuff.eps Normally C++ assumes that constants are decimal (base 10). However, for historical reasons, a number that begins with a 0 is assumed to be octal (base 8). By the same token, a number that starts with 0x or 0X is assumed to be hexadecimal, using the letters A through F or a through f for the digits beyond 9. Thus 0xFF, 0377, and 255 are all equivalent. Don’t worry if octal or hexadecimal still seem arcane — we won’t be using them in this book.

warning.eps Don’t start a constant with 0 unless you mean it to be in octal.

An integer constant can have certain symbols appended to the end to change its type. You get to see the different types of integer constants in Chapter 14.

Expressions

Variables and constants are useful only if you can use them to perform calculations. The term expression is C++ jargon for a calculation. You’ve already seen the simplest expression:

  int n;                  // declaration
n = 1;                  // expression

Programmers combine variables, constants and operators to make expressions. An operator performs some arithmetic operation on its arguments. Most operators take two arguments — these are called binary operators. A few operators take a single argument — these are the unary operators.

All expressions return a value and a type. (Note that int is the type of all the expressions described in this chapter.)

Binary operators

A binary operator is an operator that takes two arguments. If you can say var1 op var2, then op must be a binary operator. The most common binary operators are the same simple operations that you learned in grade school. The common binary operators appear in Table 4-1. (This table also includes the unary operators that are described a little later in this chapter.)

Table 4-1 Mathematical Operators in Order of Precedence

Precedence

Operator

Meaning

1

- (unary)

Returns the negative of its argument

2

++ (unary)

Increment

2

-- (unary)

Decrement

3

* (binary)

Multiplication

3

/ (binary)

Division

3

% (binary)

Modulo

4

+ (binary)

Addition

4

- (binary)

Subtraction

5

=, *=,%=,+=,-= (special)

Assignment types

The simplest binary is the assignment operator noted by the equals sign. The assignment operator says, “Take the value on the right-hand side and store at the location on the left-hand side of the operator.” (I describe the special assignment operators at the end of this chapter.)

Multiplication, division, addition, subtraction, and modulo are the operators used to perform arithmetic. They work just like the arithmetic operators you learned in grammar school, with the following special considerations:

  • Multiplication must always be expressly stated and is never implied as it is in algebra. Consider the following example:

      int n = 2;              // declare a variable
    int m = 2n;             // this generates an error

    The expression above does not assign m the value of 2 times n. Instead, C++ tries to interpret 2n as a variable name. Since variable names can’t start with a digit, it generates an error during the build step.

    What the programmer meant was:

      int n = 2;
    int m = 2 * n;          // this is OK

  • Integer division throws away the remainder. Thus, the following:

      int n = 13 / 7;         // assigns the value 1 to n

    Fourteen divided by 7 is 2. Thirteen divided by seven is 1. (Yeah, that seems weird. But hang in there. You’ll see decimal variable types that can handle fractions in Chapter 14.)

  • The modulo operator returns the remainder after division (you might not remember modulo):

      int n = 13 % 7;         // sets n to 6

    Fourteen modulo seven is zero. Thirteen modulo seven is six.

Unraveling compound expressions

A single expression can include multiple operators:

  int n = 5 + 100 + 32;

When all the operators are the same, C++ evaluates the expression from left to right:

  5 + 100 + 32
105 + 32
137

When different operators are combined in a single expression, C++ uses a property called precedence. Precedence is the order that operators are evaluated in a compound expression. Consider the following example:

  int n = 5 * 100 + 32;

What comes first, multiplication or addition? Or is this expression simply evaluated from left to right? Refer back to Table 4-1, which tells you that multiplication has a precedence of 3, which is higher than the precedence of addition which is 4 (smaller values have higher precedence). Thus multiplication occurs first:

  5 * 100 + 32
500 + 32
532

The order of the operations is overruled by the precedence of the operators. As you can see

  int n = 32 + 5 * 100;

generates the same result:

  32 + 5 * 100
32 + 500
532

But what if you really want 5 times the sum of 100 plus 32? You can override the precedence of the operators by wrapping expressions that you want performed first in parentheses, as follows:

  int n = 5 * (100 + 32);

Now the addition is performed before the multiplication:

  5 * (100 + 32)
5 * 132
660

You can combine parentheses to make expressions as complicated as you like. C++ always starts with the deepest-nested parentheses it can find and works its way out.

  (3 + 2) * ((100 / 20) + (50 / 5))
(3 + 2) * (5 + 10)
5 * 15
75

tip.eps You can always divide complicated expressions using intermediate variables. The following is safer:

  int factor = 3 + 2;
int principal = (100 / 20) + (50 / 5);
int total = factor * principal;

Assigning a name to intermediate values also allows the programmer to explain the parts of a complex equation — making it easier for the next programmer to understand.

Unary Operators

The unary operators are those operators that take a single argument. The unary mathematical operators are -, ++, and --.

The minus operator changes the sign of its argument. A positive number becomes negative, and a negative number becomes positive:

  int n = 10;
int m = -n;             // m is now -10

The ++ and the -- operators increment and decrement their arguments by one.

The increment and decrement operators are unique in that they come in two versions: a prefix and a postfix version.

remember.eps The prefix version of increment is written ++n, while the postfix is written n++.

Both the prefix and postfix increment operators increment their argument by one. The difference is in the value returned. The prefix version returns the value after the increment operation, while the postfix returns the value before the increment. (The same is true of the decrement operator.) This is demonstrated in the following IncrementOperator program:

  // IncrementOperator - demonstrate the increment operator

#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int nNumberofArgs, char* pszArgs[])
{
    // demonstrate the increment operator
    int n;

    // first the prefix
    n = 1;
    cout << "The value of n is   " <<   n << endl;
    cout << "The value of ++n is " << ++n << endl;
    cout << "The value of n afterwards is " << n << endl;
    cout << endl;

    // now the postfix
    n = 1;
    cout << "The value of n is   " <<   n << endl;
    cout << "The value of n++ is " << n++ << endl;
    cout << "The value of n afterwards is " << n << endl;
    cout << endl;

    // wait until user is ready before terminating program
    // to allow the user to see the program results
    cout << "Press Enter to continue..." << endl;
    cin.ignore(10, ' '),
    cin.get();
    return 0;
}

The output from this program appears as follows:

  The value of n is   1
The value of ++n is 2
The value of n afterwards is 2

The value of n is   1
The value of n++ is 1
The value of n afterwards is 2

Press Enter to continue …

This example demonstrates both the prefix and postfix increment. In both cases, the variable n is initialized to 1. Notice that the value of n after executing both ++n and n++ is 2. However, the value of ++n was 2 (the value after the increment), while the value of n++ was 1 (the value before the increment).

The Special Assignment Operators

The assignment operator is absolutely critical to any computer language. How else can I store a computed value? However, C++ provides a complete set of extra versions of the assignment operator — all of which seem less critical.

The authors of C++ must have noticed that expressions of the following form were very common:

  x = x # value;

Here # stands for some binary operator. In their perhaps overzealous pursuit of terseness, the authors created a separate assignment for each of the binary operators of the form:

  x #= value;  // where # is any one of the binary operators

Thus, for example

  n = n + 2;

can be written as

  n += 2;

Note: You don’t see this all that often; I present it here primarily for completeness.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.137.38