O'Reilly logo

C++ For Dummies®, 6th Edition by Stephen R. Davis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 3. Performing Mathematical Operations

In This Chapter

  • Defining mathematical operators in C++

  • Using the C++ mathematical operators

  • Identifying expressions

  • Increasing clarity with special mathematical operators

C++ offers all the common arithmetic operations: C++ programs can multiply, add, divide, and so forth. Programs have to be able to perform these operations to get anything done. What good is an insurance program if it can't calculate how much you're supposed to (over) pay?

C++ operations look like the arithmetic operations you would perform on a piece of paper, except you have to declare any variables before you can use them (as detailed in Chapter 2):

int var1;
int var2 = 1;
var1 = 2 * var2;

This code snippet declares two variables, var1 and var2. It initializes var2 to 1 and then stores the results of multiplying 2 times the value of var2 into var1.

This chapter describes the complete set of C++ mathematical operators.

Performing Simple Binary Arithmetic

A binary operator is one that has two arguments. If you can say var1 op var2, op must be a binary operator. The most common binary operators are the simple operations you performed in grade school. The binary operators are flagged in Table 3-1. (This table also includes the unary operators, which I describe a little later in this chapter.)

Table 3.1. Mathematical Operators in Order of Precedence

Precedence

Operator

What It Is

1

+ (unary)

Effectively does nothing

1

- (unary)

Returns the negative of its argument

2

++ (unary)

Increment

2

-- (unary) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required