Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

C++ PROGRAMMING LANGUAGE COURSE 2 - Expressions, Study notes of Computer Programming

EXPRESSIONS: Arithmetic, relational, logical, bitwise, increment/decrement, assignment, conditional, coma operators, the size of operator, operator precedence, simple type conversion and an exercise

Typology: Study notes

2022/2023

Available from 07/29/2023

dennis-durfort
dennis-durfort 🇺🇸

16 documents

1 / 10

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
EXPRESSIONS: Arithmetic, relational, logical, bitwise, increment/decrement, assignment, conditional,
coma operators, the size of operator, operator precedence, simple type conversion and an exercise
C++ PROGRAMMING LANGUAGE
COURSE 2 - Expressions
2. Expressions
This chapter introduces the built-in C++ operators for composing expressions.
An expression is any computation which yields a value.
When discussing expressions, we often use the term evaluation. For
example, we say that an expression evaluates to a certain value. Usually the final
value is the only reason for evaluating the expression. However, in some cases,
the expression may also produce side-effects. These are permanent changes in the
program state. In this sense, C++ expressions are different from mathematical
expressions.
C++ provides operators for composing arithmetic, relational, logical, bitwise,
and conditional expressions. It also provides operators which produce useful
side-effects, such as assignment, increment, and decrement. We will look at each
category of operators in turn. We will also discuss the precedence rules which
govern the order of operator evaluation in a multi- operator expression.
Arithmetic Operators
C++ provides five basic arithmetic operators. These are summarized in Table 2.1.
Table 2.1 Arithmetic operators.
Operator Name Example
+Addition 12 + 4.9 // gives 16.9
-Subtraction 3.98 - 4 // gives -0.02
*Multiplicati
on
2 * 3.4 // gives 6.8
/Division 9 / 2.0 // gives 4.5
%Remainder 13 % 3 // gives 1
Except for remainder (%) all other arithmetic operators can accept a mix of
integer and real operands. Generally, if both operands are integers then the result
will be an integer. However, if one or both of the operands are reals then the
result will be a real (or double to be exact).
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download C++ PROGRAMMING LANGUAGE COURSE 2 - Expressions and more Study notes Computer Programming in PDF only on Docsity!

coma operators, the size of operator, operator precedence, simple type conversion and an exercise

C++ PROGRAMMING LANGUAGE

COURSE 2 - Expressions

2. Expressions

This chapter introduces the built-in C++ operators for composing expressions. An expression is any computation which yields a value. When discussing expressions, we often use the term evaluation. For example, we say that an expression evaluates to a certain value. Usually the final value is the only reason for evaluating the expression. However, in some cases, the expression may also produce side-effects. These are permanent changes in the program state. In this sense, C++ expressions are different from mathematical expressions. C++ provides operators for composing arithmetic, relational, logical, bitwise, and conditional expressions. It also provides operators which produce useful side-effects, such as assignment, increment, and decrement. We will look at each category of operators in turn. We will also discuss the precedence rules which govern the order of operator evaluation in a multi- operator expression. Arithmetic Operators C++ provides five basic arithmetic operators. These are summarized in Table 2.1. Table 2.1 Arithmetic operators. Operator Name Example

  • Addition 12 + 4.9 // gives 16.
  • Subtraction 3.98 - 4 // gives -0.
  • Multiplicati on 2 * 3.4 // gives 6. / Division 9 / 2.0 // gives 4. % Remainder 13 % 3 // gives 1 Except for remainder (%) all other arithmetic operators can accept a mix of integer and real operands. Generally, if both operands are integers then the result will be an integer. However, if one or both of the operands are reals then the result will be a real (or double to be exact).

coma operators, the size of operator, operator precedence, simple type conversion and an exercise

When both operands of the division operator (/) are integers then the division is performed as an integer division and not the normal division we are used to. Integer division always results in an integer outcome (i.e., the result is always rounded down). For example: 9 / 2 // gives 4, not 4.5! -9 / 2 // gives -5, not -4! Unintended integer divisions are a common source of programming errors. To obtain a real division when both operands are integers, you should cast one of the operands to be real: int cost = 100; int volume = 80; double unitPrice = cost / (double) volume; // gives

The remainder operator (%) expects integers for both of its operands. It returns the remainder of integer-dividing the operands. For example 13%3 is calculated by integer dividing 13 by 3 to give an outcome of 4 and a remainder of 1; the result is therefore 1. It is possible for the outcome of an arithmetic operation to be too large for storing in a designated variable. This situation is called an overflow. The outcome of an overflow is machine-dependent and therefore undefined. For example: unsigned char k = 10 * 92; // overflow: 920 > 255 It is illegal to divide a number by zero. This results in a run-time division-by-zero failure which typically causes the program to terminate.  Relational Operators C++ provides six relational operators for comparing numeric quantities. These are summarized in Table 2.2. Relational operators evaluate to 1 (representing the true outcome) or 0 (representing the false outcome). Table 2.2 Relational operators. Operator Name Example == Equality 5 == 5 // give s

!= Inequality 5 != 5 // give s

< Less Than 5 < 5.5 // give s

<= Less Than or Equal 5 <= 5 // give s

(^) Greater Than 5 > 5.5 // give s

= Greater Than or 6.3 >= 5 // give 1

coma operators, the size of operator, operator precedence, simple type conversion and an exercise

10 || 5.5 // gives 1 10 && 0 // gives 0 C++ does not have a built-in boolean type. It is customary to use the type int for this purpose instead. For example: int sorted = 0; // false int balanced = 1; // true Bitwise Operators C++ provides six bitwise operators for manipulating the individual bits in an integer quantity. These are summarized in Table 2.4. Table 2.4 Bitwise operators. Operator Name Example ~ Bitwise Negation ~'\011' // gives '\366' & Bitwise And '\011' & '\027' // gives '\001' | Bitwise Or '\011' | '\027' // gives '\037' ^ Bitwise Exclusive Or '\011' ^ '\027' // gives '\036' << Bitwise Left Shift '\011' << 2 // gives '\044'

Bitwise Right Shift '\011' >> 2 // gives '\002' Bitwise operators expect their operands to be integer quantities and treat them as bit sequences. Bitwise negation is a unary operator which reverses the bits in its operands. Bitwise and compares the corresponding bits of its operands and produces a 1 when both bits are 1, and 0 otherwise. Bitwise or compares the corresponding bits of its operands and produces a 0 when both bits are 0, and 1 otherwise. Bitwise exclusive or compares the corresponding bits of its operands and produces a 0 when both bits are 1 or both bits are 0, and 1 otherwise. Bitwise left shift operator and bitwise right shift operator both take a bit sequence as their left operand and a positive integer quantity n as their right operand. The former produces a bit sequence equal to the left operand but which has been shifted n bit positions to the left. The latter produces a bit sequence equal to the left operand but which has been shifted n bit positions to the right. Vacated bits at either end are set to 0. Table 2.5 illustrates bit sequences for the sample operands and results in Table 2.4. To avoid worrying about the sign bit (which is machine dependent), it is common to declare a bit sequence as an unsigned quantity: unsigned char x = '\011'; unsigned char y = '\027'; Table 2.5 How the bits are calculated. Example Octal Value Bit Sequence x 011 0 0 0 0 1 0 0 1 y 027 0 0 0 1 0 1 1 1 ~x 366 1 1 1 1 0 1 1 0

coma operators, the size of operator, operator precedence, simple type conversion and an exercise

x & y 001 0 0 0 0 0 0 0 1 x | y 037 0 0 0 1 1 1 1 1 x ^ y 036 0 0 0 1 1 1 1 0 x << 2 044 0 0 1 0 0 1 0 0 x >> 2 002 0 0 0 0 0 0 1 0 Increment/Decrement Operators The auto increment (++) and auto decrement (--) operators provide a convenient way of, respectively, adding and subtracting 1 from a numeric variable. These are summarized in Table 2.6. The examples assume the following variable definition: int k = 5; Table 2.6 Increment and decrement operators. Operator Name Example ++ (^) Auto Increment (prefix) ++k + 10 // give s

++ Auto Increment (postfix) k++ + 10 // give s

-- Auto Decrement (prefix) --k + 10 // give s

-- Auto Decrement (postfix) k-- + 10 // give s

Both operators can be used in prefix and postfix form. The difference is significant. When used in prefix form, the operator is first applied and the outcome is then used in the expression. When used in the postfix form, the expression is evaluated first and then the operator applied. Both operators may be applied to integer as well as real variables, although in practice real variables are rarely useful in this form. Assignment Operator The assignment operator is used for storing a value at some memory location (typically denoted by a variable). Its left operand should be an lvalue, and its right operand may be an arbitrary expression. The latter is evaluated and the outcome is stored in the location denoted by the lvalue. An lvalue (standing for l eft value ) is anything that denotes a memory location in which a value may be stored. The only kind of lvalue we have seen so far in this book is a variable. Other kinds of lvalues (based on pointers and references) will be described later in this book. The assignment operator has a number of variants, obtained by combining it with the arithmetic and bitwise operators. These are summarized in Table 2.7. The examples assume that n is an integer variable. Table 2.7 Assignment operators. Operator Example Equivalent To = n = 25 += n += 25 n = n + 25

coma operators, the size of operator, operator precedence, simple type conversion and an exercise

operand of another conditional operation, that is, conditional expressions may be nested. For example: int m = 1, n = 2, p =3; int min = (m < n? (m < p? m : p) : (n < p? n : p)); Comma Operator Multiple expressions can be combined into one expression using the comma operator. The comma operator takes two operands. It first evaluates the left operand and then the right operand, and returns the value of the latter as the final outcome. For example: int m, n, min; int mCount = 0, nCount = 0; //... min = (m < n? mCount++, m : nCount++, n); Here when m is less than n, mCount++ is evaluated and the value of m is stored in min. Otherwise, nCount++ is evaluated and the value of n is stored in min. The sizeof Operator C++ provides a useful operator, sizeof, for calculating the size of any data item or type. It takes a single operand which may be a type name (e.g., int) or an expression (e.g., 100) and returns the size of the specified entity in bytes. The outcome is totally machine-dependent. Listing 2.1 illustrates the use of sizeof on the built-in types we have encountered so far. Listing 2. 1 2 3 4 5 6 7 8 9 10 #include <iostream.h> int main (void) { cout << "char size = " << sizeof(char) << " bytes\n"; cout << "char* size = " << sizeof(char*) << " bytes
n"; cout << "short size = " << sizeof(short) << " bytes\n"; cout << "int size = " << sizeof(int) << " bytes\n"; cout << "long size = " << sizeof(long) << " bytes\n"; cout << "float size = " << sizeof(float) << " bytes\n"; cout << "double size = " << sizeof(double) << " bytes\n"; cout << "1.55 size = " << sizeof(1.55) << " bytes\n"; cout << "1.55L size = " << sizeof(1.55L) << " bytes
n"; cout << "HELLO size = " << sizeof("HELLO") << " bytes\n";

coma operators, the size of operator, operator precedence, simple type conversion and an exercise

When run, the program will produce the following output (on the author’s PC): char size = 1 bytes char* size = 2 bytes short size = 2 bytes int size = 2 bytes long size = 4 bytes float size = 4 bytes double size = 8 bytes 1.55 size = 8 bytes 1.55L size = 10 bytes HELLO size = 6 bytes Operator Precedence The order in which operators are evaluated in an expression is significant and is determined by precedence rules. These rules divide the C++ operators into a number of precedence levels (see Table 2.8). Operators in higher levels take precedence over operators in lower levels. Table 2.8 Operator precedence levels. Level Operator Kind Order Highes t :: Unary Both () [] ->. Binary Left to Right

new delete sizeof () Unary^ Right^ to^ Left ->* .* Binary Left to Right

  • / % Binary Left to Right
    • Binary Left to Right << >> Binary Left to Right < <= > >= Binary Left to Right == != Binary Left to Right & Binary Left to Right ^ Binary Left to Right | Binary Left to Right && Binary Left to Right || Binary Left to Right ? : Ternary Left to Right = (^) += -=

^=

= Binary^ Right^ to^ Left Lowest , Binary Left to Right For example, in

coma operators, the size of operator, operator precedence, simple type conversion and an exercise

match the type of i on the left side of the assignment, so it is converted to int ( demoted ) before being assigned to i. The above rules represent some simple but common cases for type conversion. More complex cases will be examined later in the book after we have discussed other data types and classes. Exercises 1.1 Write expressions for the following:  To test if a number n is even.  To test if a character c is a digit.  To test if a character c is a letter.  To do the test: n is odd and positive or n is even and negative.  To set the n -th bit of a long integer f to 1.  To reset the n -th bit of a long integer f to 0.  To give the absolute value of a number n.  To give the number of characters in a null-terminated string literal s. 1.2 Add extra brackets to the following expressions to explicitly show the order in which the operators are evaluated: (n <= p + q && n >= p - q || n == 0) (++n * q-- / ++p - q) (n | p & q ^ p << 2 + q) (p < q? n < p? q * n - 2 : q / n + 1 : q - n) 1.3 What will be the value of each of the following variables after its initialization: double d = 2 * int(3.14); longk = 3.14 - 3; charc = 'a' + 2; charc = 'p' + 'A' - 'a'; 1.4 Write a program which inputs a positive integer n and outputs 2 raised to the power of n. 1.5 Write a program which inputs three numbers and outputs the message Sorted if the numbers are in ascending order, and outputs Not sorted otherwise.