Arithmetic Operations and Expressions
-
In an arithmetic expression, the type of the value produced and
the value of the result can depend on the type of the data involved
-
In any assignment statement
Variable = Expression
involving an expression,
the expression is first evaluated and then the result is assigned to the variable on the left
-
Example:
int integer1 = 11, integer2 = 4, integer3;
double double1= 11.0, double2 = 4.0, double3;
integer3 = integer1 / integer2; // integer3 has the value of 2
integer4 = integer1 % integer2; // integer4 is 3
double3 = integer1 / integer2; // double3 has the value of 2.00
double3 = double1 / double2; // double3 has the value of 2.75
-
The quotient of 2 integers is given by the integer obtained from the result by dropping the fractional part
(not rounding). The remainder. if any, can be retrieved using the % operator, which is defined for integer operation only.
-
In an arithmetic operation involving an integer and a double, the integer is first converted
to a double, and the operation is carried out and the result is a double value
-
Results of operations using / and % with negative integers can differ depending on the compiler,
and therefore should be avoided
-
An expression that has more than one operator can have the order of operation changed by proper use of parentheses
For example, the following 2 expressions give different results
(x + y) * z;
x + (y * z);
-
In the absence of parentheses, the computer follows the so-called precedence rules to determine the actual order of operations.
-
High precedence operators must be carried out first.
-
Operators having the same level of precedence are evaluated from left to right
-
A complete set C++ precedence rules are given in Appendix 2.
Operators are listed from high to low precedence.
Operator having the same level of precedence are grouped together.
-
For example, you will find the following operators list:
! not
------------------------------
- unary minus
+ unary plus
------------------------------
* multiplication
/ division
% integer remainder (modulo)
------------------------------
+ addition
- subtraction
------------------------------
= assignment
-
Use parentheses if you have any doubt about the precedence of the operators
-
The use of parentheses also helps to improve the readability of the expression
-
C++ has a shorthand notation of the general form:
Variable Operator = Expression
which is defined to be equivalent to
Variable = Variable Operation (Expression)
Examples:
count += 2;
// count = count + 2;
cost -= discount;
// cost = cost - discount;
position += velocity * time; // position = position + velocity * time;
change %= 100;
// change = change % 100;
-
One must be careful when writing expressions from mathematical formulas