A unary operator is an operator which requires one operand only. For example, the negative sign (-) in the number "-10" is a unary operator.
A binary operator is an operator which requires two operands, one on the left and the other on the right.
When writing expressions, parentheses () (singular: parenthesis) are used to group expressions which are to be performed first, or just for increasing readability of the program.
The following table shows five arithmetic operators (addition, subtraction, multiplication, division and modulus). They are all binary operators.
Operator in C++ | Operation | Sample C++ expression | Equivalent Pascal expression |
+ | Addition | p + q | p + q |
- | Subtraction | m - n | m - n |
* | Multiplication | a * b | a * b |
/ (See Program 3) | Division | x / y | x div y (if both x and y
are of integer types) x / y (if at least one operand is of floating point type) |
% | Modulus | r % s | r mod s |
The following program demonstrates how the data types of the operands affect the results of division:
#include <iostream.h> main() { int i = 17, j = 5; float x = 17, y, z; cout << i / j << endl; // 3 (NOT 3.4) will be displayed. // Note that i & j are of type int while x is of type float. y = i / j; // 3 will be stored in y. cout << y << endl; z = x / j; // 3.4 will be stored in z. cout << z << endl; // Compare the following: cout << 18 / 8 << endl; // 2 will be displayed. cout << 18.0 / 8 << endl; // 2.25 will be displayed. cout << 18 / 8.0 << endl; // 2.25 will be displayed. cout << 18.0 / 8.0 << endl; // 2.25 will be displayed. return 0; } |
C++ expression | Equivalent Pascal expression |
(x + y - a) % b | (x + y - a) mod b |
#include <iostream.h> main() { char c1 = 'A', // The ASCII code of 'A' is 65. c2; int i; float x; c2 = c1 + 5; // 'F' (ASCII code = 65+5 = 70) is stored in c2. cout << c2 << endl; x = -0.25; i = c2 * x; // -17 [integer part of 70*(-0.25) = -17.5] is ... cout << i << endl; // ... stored in i. return 0; } |