Tutorial#13 - Expressions in C++

Expressions in C++

Expressions:

There are three types of arithmetic expressions in C++:
1: Integral expressions—all operands in the expression are integers. An integral expression yields an integral result.
2: Floating-point (decimal) expressions—all operands in the expression are floating points (decimal numbers). A floating-point expression yields a floating-point result.
3: Mixed expressions—the expression contains both integers and decimal numbers. Looking at some examples will help clarify these definitions.
Consider the following C++ integral expressions:
2 + 3 * 5
3 + x - y / 7
x + 2 * (y - z) + 18
In these expressions, x, y, and z are variables of type int.
Consider the following C++ floating-point expressions:
12.8 * 17.5 - 34.50
x * 10.5 + y - 16.2
Here, x and y are variables of type double.

Mixed Expressions:

An expression that has operands of different data types is called a mixed expression. A mixed expression contains both integers and floating-point numbers. The following expressions are examples of mixed expressions:
2 + 3.5
6 / 4 + 3.9
5.4 * 2 - 13.6 + 18 / 2
Two rules apply when evaluating a mixed expression:
1: When evaluating an operator in a mixed expression:
(a) If the operator has the same types of operands (that is, either both integers or both floating-point numbers), the operator is evaluated according to the type of operands. Integer operands thus yield an integer result; floating-point numbers yield a floating-point number.
(b) If the operator has both types of operands (that is, one is an integer and the other is a floating-point number), then during calculation, the integer is changed to a floating-point number with the decimal part of zero and the operator is evaluated. The result is a floating-point number.
2: The entire expression is evaluated according to the precedence rules; the multiplication, division, and modulus operators are evaluated before the addition and subtraction operators. Operators having the same level of precedence are evaluated from left to right. Grouping using parentheses is allowed for clarity.

The following C++ program evaluates the preceding expressions:
// This program illustrates how mixed expressions are evaluated.
#include <iostream>
using namespace std;
int main()
{
cout << "3 / 2 + 5.5 = " << 3 / 2 + 5.5 << endl;
cout << "15.6 / 2 + 5 = " << 15.6 / 2 + 5 << endl;
cout << "4 + 5 / 2.0 = " << 4 + 5 / 2.0 << endl;
cout << "4 * 3 + 7 / 5 - 25.5 = "<< 4 * 3 + 7 / 5 - 25.5 << endl;
return 0;
}

Sample Run:
3 / 2 + 5.5 = 6.5
15.6 / 2 + 5 = 12.8
4 + 5 / 2.0 = 6.5
4 * 3 + 7 / 5 - 25.5 = -12.5

Comments