Operators for Fundamental Types

In this chapter, operators needed for calculations and selections are introduced. Overloading and other operators, such as those needed for bit manipulations, are introduced in later chapters.

Binary Arithmetic Operators

Binary operator and operands

The binary arithmetic operators


Sample program

#include <iostream>
using namespace std;
int main()
{
   double x, y;
   cout << "\nEnter two floating-point values: ";
   cin >> x >> y;
   cout << "The average of the two numbers is: "
        << (x + y)/2.0 << endl;
   return 0;
} 

Sample output for the program

    Enter two floating-point values:  4.75   12.3456
    The average of the two numbers is: 8.5478 
If a program is to be able to process the data input it receives, you must define the operations to be performed for that data. The operations being executed will depend on the type of data — you could add, multiply, or compare numbers, for example. However, it would make no sense at all to multiply strings.
The following sections introduce you to the most important operators that can be used for arithmetic types. A distinction is made between unary and binary operators. A unary operator has only one operand, whereas a binary operator has two.

Binary Arithmetic Operators

Arithmetic operators are used to perform calculations. The opposite page shows an overview. You should be aware of the following:
  • Divisions performed with integral operands will produce integral results; for example, 7/2 computes to 3. If at least one of the operands is a floating-point number, the result will also be a floating-point number; e.g., the division 7.0/2 produces an exact result of 3.5.
  • Remainder division is only applicable to integral operands and returns the remainder of an integral division. For example, 7%2 computes to 1.

Expressions

In its simplest form an expression consists of only one constant, one variable, or one function call. Expressions can be used as the operands of operators to form more complex expressions. An expression will generally tend to be a combination of operators and operands.
Each expression that is not a void type returns a value. In the case of arithmetic expressions, the operands define the type of the expression.
Examples:
int a(4);  double x(7.9);
a * 512          // Type int
1.0 + sin(x)     // Type double
x – 3          // Type double, since one
               // operand is of type double 
An expression can be used as an operand in another expression.
Example:
2 + 7 * 3              // Adds 2 and 21 
Normal mathematical rules (multiplication before addition) apply when evaluating an expression, i.e. the *, /, % operators have higher precedence than + and -. In our example, 7*3 is first calculated before adding 2. However, you can use parentheses to apply a different precedence order.
Example:
(2 + 7) * 3        // Multiplies 9 by 3. 

Post a Comment

0 Comments