Numerical operators and expressions Rules of precedence

More C++ Basics
1
Numerical operators and expressions
In C++ the symbols used for addition and subtraction are the usual symbols + and -. The
symbol for multiplication is *. There are two division operators, whose symbols are / and
%.


When the / operator is used to perform division, the data types of the operands can
affect the result of the computation. This is explained in the following two cases.
If both operands are integer types, the operator / returns the integer quotient,
throwing away the remainder. Therefore
5 / 2 = 2
4 / 5 = 0

If one of the two operands to the division operator / is of type double, then the
operator / does the normal division and the result is of type double. Therefore
5 / 2. = 2.5
2. / 5 = 0.4

The operator % is called the remainder (or modulus) operator. When using this
operator, both operands must be integer types. This operator returns the remainder
(or modulus) of the first operand divided by the second. Therefore,
9 % 2 = 1
8 % 2 = 0
Rules of precedence
Consider the algebraic expression: 2 + 3 * 4.
We know that the value is 14 but not 20, because we must evaluate the expression as 2 +
(3 * 4).
The reason for first evaluating 3 * 4 is that (as in algebra) multiplication has higher
precedence than addition, so multiplication is performed first.
More C++ Basics
2
Precedence of numerical operators
Precedence
Higher
Lower
Numerical operator
*, /, %
+, -
Operations with the same precedence level
If an expression with no parentheses contains two operators of the same precedence, the
computer performs those operations in order from left to right. Operations within
parentheses are performed first. We use parentheses when we need to override the
normal precedence order.
Therefore, if we want the computer to multiply a+b with c, we have to write
( a + b ) * c
Likewise, if we want a+b to be divided by c+d, then we have to write
( a + b ) / (c + d)
Note that if we write
a + b / c + d
then it would get evaluated as
a + ( b / c ) + d
Look at the following expressions and their correct values. We evaluated the expressions
using the rules of precedence. Remember that these numbers, as they are not followed
by a decimal point, are interpreted by the compiler as integers, and so integer
mathematics is used.
Expression
1-2/3+4
-1+5/2*3
(1 + 2) / ( 3 * 4)
Value
5
5
0
More C++ Basics
1+2/3*4
3
1
Type casting
If there is a need, we can convert (temporarily) an integer operand to a double in a
computation by using something called a “static cast.” The compiler will generate an error
if no conversion exists between the source type and the destination type.
Suppose that i and j are of type int. The expression
static_cast<double>(i) / j
results in a value of type double and therefore becomes ordinary division. The syntax of a
cast may be a bit confusing right now, because it uses a language feature called
“templates.” However, if you continue to use the syntax for now, the meaning will
become clearer when we discuss templates in a future lecture.
For example consider this code segment
double a, b;
auto i = 7, j = 2;
a = static_cast<double>(i) / j; // type of i is cast as double
b = i / j;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
produces the output:
a = 3.5
b = 3
In the statement a = static_cast<double>(i) / j, the value of i is cast to type double, by
placing i in parentheses and preceding it by the keyword double. Thus, i will be treated as
a double value. However, in the next statement variable i has its original type, int.
There are other casts besides static_cast, such as dynamic_cast and reinterpret_cast.
However, we will not discuss these until later in the course.
More C++ Basics
4
Legacy Language Feature Warning
You may see casts written in the following syntax in older C++ code:
double d = 5.5;
int i = (int)d;
In even older code, you might see it written as:
double d = 5.5;
int i = int(d);
While both of these casts will work, they are dangerous because they combine several
different and unique forms of casts into one operation. As a result, we will consider them
legacy language features for CS 570 and you should not use them.
More assignment statements
There is a shorthand notation that combines the assignment operator (=) with any one of
the numerical operators.
Any of the numerical operators +, -, *, /, and %, can be combined with the assignment
operator to create an arithmetic assignment operator.
These operators are +=, -=, *=, /=, and %=. Each consists of two operators and should not
have blank spaces between them.
The general form to use these assignments is
variable OP= expression;
which is equivalent to
variable OP= variable OP ( expression );
For example,
current_count += previous_count;
is same as
More C++ Basics
current_count = current_count + previous_count;
5
More C++ Basics
6
Below are more examples.
Example
sum += 2;
total -= loan;
product *= n + 4;
share /= 5;
change %= 100;



Same as
sum = sum + 2;
total = total - loan;
product = product * ( n + 4 );
share = share / 5;
change = change % 100;
In an arithmetic assignment operator, the arithmetic operator precedes the
assignment operator =. That is these operators +=, -=, *=, /=, and %=.
Reversing the order of the individual operators may cause either a syntax error or an
unexpected result at run time. For example:
a =* b;
// syntax error
a =+ b;
// OK, but this not a = a+b. It is a = +b,
or simply a = b
Arithmetic assignment operators are not required. However, they are used to
abbreviate assignment statements in which the variable to the left of the assignment
operator also appears in the expression on the right.
For extremely simple cases where you merely want to increment or decrement a variable
by 1, C++ has an even simpler syntax for this: (In fact, this is where it gets its name!)
auto i = 0;
i++; // i now equals 1
i--; // i once again now equals 0
Named constants
A constant is a value that is fixed. Examples of constants are the number of feet per yard,
number of centimeters per inch.
We can declare a named constant by using the const keyword like this.
More C++ Basics
7
const double CTMR_PER_INCH = 2.54;
The value of a constant remains fixed throughout the program. Statements within a
program must not attempt to modify the value of a constant.
The rules for creating identifiers, discussed before, also apply to making up names for
constants. It is a common practice in some C++ circles to use upper case letters in constant
identifiers. For the variable identifiers we use lower case letters. These are stylistic
conventions. Following such a convention makes it easy to tell whether an identifier is a
constant or a variable.
There are good reasons for using constant identifiers.
•
Referring to a certain fixed value by name can help make a program easier to
understand. For example, the descriptive name CTMR PER INCH would mean more to
most readers than the number 2.54.
•
Some frequently used constants (such as 3 .14159) are easy to mistype, and the
compiler does not catch this kind of error. Referring to such constants by name PI
guarantees that in a given program we always use the same value for the constant.
•
A constant is assigned its value only once in a program, but may be referred to
many times in the program. Therefore, if at a later date the value of a constant is changed,
the program can be updated easily.
In C++ there are many predefined constants. For example, as we have discussed before,
INT MIN and INT MAX equal the smallest and largest int values.
The char data type
A variable of type char can be used to store any single character value. Examples of a
character value are a letter, a digit, or a punctuation mark. A character value in C++ is
enclosed in single quote marks. We have seen before that a string of characters (also
called string literals), is enclosed in double quote marks.
For example
char grade;
grade = ’A’; // stores A without quotes
There are three characters that are known as white space characters. They produce blank
(white) space when they are printed. These are blank character, new line character, and
More C++ Basics
8
horizontal tab. Whitespace characters are used to separate data inputs to a program.
When reading a value into a char variable, the program skips over whitespace characters.
Consider the following program:
#include <iostream>
using namespace std;
int main()
{
char x1, x2, x3;
cout << "Enter Three Characters:";
cin >> x1 >> x2 >> x3;
cout << x1 << x2 << x3;
return 0;
}
When the program is run with the user inputs, the output on the screen is as follows.
Enter Three Characters:
A←
B
←
C
←
ABC
In the screen display shown above, by the symbol ←, we mean that the user pressed the
Enter key.
Computer representation of characters
Each character is represented by a one-byte (8-bit) code. The computer uses the American
Standard Code for Information Interchange (ASCII code), pronounced ”as-key code”.
For example, the letter ‘A’ is represented internally as binary 01000001 which is equal to
decimal 65.
Unfortunately, ASCII does not support many larger character sets such as Chinese
language symbols. There is no built-in support for
Appendix 3 (page 958) of your text book contains a table of characters and their ASCII
codes.
More C++ Basics
9
Type casts with char and int
Type casts can be used to convert between characters and their ASCII codes. Suppose ch
is a char, then static_cast<int>(ch) will be its ASCII code, and if n is an integer from 0 to
255 (the range of ASCII codes), static_cast<char>(n) will be the character having ASCII
code n.
For example this code segment
cout << ’C’ << " " << static_cast<int>(’C’) << endl;
cout << static_cast<int>(67) << " " << 67 << endl;
cout << static_cast<int>(’C’ + 1) << " " << ’C’ + 1 << endl;
produces the output:
C 67
C 67
D 68
Lexicographic ordering of characters
All ASCII characters are in an extended alphabetical or lexicographic ordering based on
their ASCII codes.
Hence, ’a’ < ’b’ because the ASCII code for ’a’ is 97 which is less than that of ’b’ whose ASCII
code 98. Similarly, when comparing two uppercase letters, the < operator obeys the
normal alphabetical order.
The string data type
The string data type contains a series of char organized in a way as described by the
programmer. It is actually a “user-defined type;” however, you do not need to concern
yourself with this yet except that in order to use it, you will need to include the header
<string>.
Here is an example use of string:
string str = "Hello world";
cout << str << endl;
When using "literal text" to enter a literal string in code, you are actually using a more
advanced feature called “C strings.” We will discuss C strings in greater depth in a future
More C++ Basics
10
lecture, but it is important to be aware that what is actually happening here is the
compiler is automatically converting your C string into a C++ string, because you specified
string as the data type that you are using to create your variable. However, you cannot
use auto to create your variable, because type inference will cause your variable to be
typed as a C string. If you find this confusing, don’t worry about it too much for now, and
just avoid auto in conjunction with strings.
The bool data type
Expressions of type bool are called Boolean after the mathematician George Boole, the
formulator of rules for mathematical logic.
Boolean expressions evaluate to one of two values, true or false. Boolean expressions are
used in branching and looping statements that we study soon.
Escape sequences
We have seen earlier that output statements can contain string literals. A string literal is
a sequence of characters enclosed between double quote characters. But how would we
display a string literal such as
I said to him, "That is cool".
If we use the statement
cout << "I said to him, "That is cool".";
we would get a syntax error message saying that the compiler expects a colon after the
second double quote mark. The compiler does not assume that second double quote is
part of the string literal. It believes that the second double quote ends the string literal.
We can resolve this misunderstanding by using the slash character \, to cause an ”escape”
from the way the compiler normally interprets characters.
We rewrite the output statement as
cout << "I said to him, \"That is cool\".";
The escape sequence, \", lets the compiler know that the double quote character is part
of the string literal. Note that the backslash character will not be displayed.
More C++ Basics
11
Now, what if we have a single backslash character appearing in a string literal that we
want to display. For example we want to output
c:\mydir\cpp_files\mypro.cpp
We can again use an escape sequence like this \\. The first backslash in \\ introduces an
escape sequence, and the second says that \ is to be output.
So we can write our output statement as
cout << "c:\\mydir\\cpp_files\\mypro.cpp";
C++ supports some other escape sequences as well. These escape sequences cause the
compiler to put special characters, called control characters, on the output stream. For
example, the escape sequence \n causes output to move to the beginning of a new line.
Indeed, \n is called the newline character. The escape sequence \a causes the computer’s
speaker to beep, though for historical reasons, \a is called the bell character.
For example this code segment
cout << "This code\nuses the\n";
cout << "newline character.\n";
cout << "This line makes the speaker beep\a.";
produces the output
This code uses the
newline character.
This line makes the speaker beep