Introduction to C / Operators

Total Page:16

File Type:pdf, Size:1020Kb

Introduction to C / Operators

Introduction to C++ / Operators

Topics

 Arithmetic in C++

 Rules of operator precedence

 Relational operators

 Logical operators

 Increment and decrement operators

 Bitwise operators

1- Arithmetic in C++

The C++ arithmetic operators are summarized in Fig. 1

Note: The remainder operator is an integer operator that can be used only with integer operands. The expression x % y yields the remainder after x is divided by y. Thus, 7 % 4 yields 3 and 17 % 5 yields 2. Note: attempt to divide by zero is normally undefined on computer systems and generally results in a fatal error, i.e., an error that causes the program to terminate immediately without having successfully performed its job. Nonfatal errors allow programs to run to completion, often producing incorrect results. Note: Parentheses for Grouping Sub-expressions, to multiply N times the quantity a + b it is written as follows: N * ( a + b ).

2- Rules of Operator Precedence C++ applies the operators in arithmetic expressions in a precise sequence determined by the following rules of operator precedence, which are generally the same as those in algebra.

1- Operators in expressions contained within pairs of parentheses are evaluated first. Thus, parentheses may be used to force the order of evaluation to occur in any sequence the programmer needs. Therefore, parentheses have the highest level of precedence.

Ex: ( ( a + b ) + c ) the operators in the innermost pair of parentheses are applied first. 2- Multiplication, division and remainder operations are applied first. If a expression contains several multiplication, division and remainder operations, evaluation proceeds from left to right. Multiplication, division and remainder are said to be on the same level of precedence.

3- Addition and subtraction operations are evaluated next. If an expression contains several addition and subtraction operations, evaluation proceeds from left to right. Addition and subtraction also have the same level of precedence, which is lower than the precedence of the multiplication, division and remainder operations.

4- The rules of operator precedence specify the order C uses to evaluate expressions, and when it is said evaluation proceeds from left to right, it means the associativity of operators. Fig. 2 summarizes the rules of precedence and states the associativity of the operators mentioned above.

Ex1: Write the C++ expression for the following algebraic equation:

Algebra m= C++ m= (a+b+c+d+e)/5 ; The parentheses are required to group the additions because division has higher precedence than addition. The entire quantity ( a + b + c + d + e ) should be divided by 5. If the parentheses are omitted, what we obtained shall be a+b+c+d+e/5 which evaluates incorrectly as: m=

Ex2: The following is a straight line equation y= mx + b the C++ equivalent expression can be written as follows: y = m*x + b. There is no need for parentheses. The multiplication is evaluated first because multiplication has a higher precedence than addition.

Ex3: The following equation contains remainder (%), multiplication, division, addition, subtraction and assignment operations:

Algebra: z = p.r%q + w/x – y the sequence of operations should be as depicted below:

p is multiplied by r, then the result is applied to the remainder operator (%). Thirdly w is divided y x. Finally, the addition and subtraction are made. For more clarity: z = p.r %q + w/x – y 3- Relational Operators

C++ provides six relational operators to compare numbers. Each relational expression reduces to the bool value true if the comparison is true and to the bool value false if the comparison is false, so these operators are well suited for use in a loop test expression. However, the use of relational operators is inherent to appearance of conditional statements represented by the if-statement. Conditions in if statements are formed by using the equality operators and relational operators summarized in Fig. 4 The relational operators all have the same level of precedence and they associate left to right.

4- Logical Operators

Relational and equality operators can be used to implement simple conditions such as counter <= 10, deposit > 1000, result != 10 etc.

To test multiple conditions in the process of making a decision, it is needed to perform these tests in separate statements or in nested if or if…else statements.

C++ provides logical operators that may be used to form more complex conditions by combining simple conditions. The logical operators are && (logical AND), || (logical OR) and ! (logical NOT also called logical negation).

If it is needed to ensure that two conditions are both true before choosing a certain path of execution. In this case, the logical operator is used as follows:

If (condition1 is true && condition2 is true) // then execute the following statements Statement 1 Statement 2 For more clarity suppose it’s needed to classify library books according to several categories include: philosophy (1), science (2), medicine (3) and according to their publication year whether it was in 1990, 2000 or 2010. In such case the following decision statement can be written:

If (category == 1 && publication >= 2010)

new_philisophy = new_philosophy + 1 ;

In the previous case, it was compulsory for the two conditions to be true in order to execute the following statement(s) since the && logical operator is used. The logical || OR operator can provide different functionality that what is obtained with the logical AND, where only one of tested conditions must be true to let the following statement be executed as shown in the following example: if ( semester_Average >= 90 || final_Exam >= 90 ) cout<< "Student grade is A" << endl ;

5- Increment and decrement operators

The increment and decrement operators are used commonly in loop operations: increasing and decreasing a loop counter by one. Each operator comes in two varieties (prefix and postfix). The prefix version comes before the operand, as in ++x. The postfix version comes after the operand, as in x++. The two versions have the same effect on the operand, but they differ in terms of when they take place. Code in listing1 demonstrates this difference for the increment operator.

Listing1

#include int main( ) { int a = 20; int b = 20;

cout << “a = “ << a << “: b = “ << b << endl ; cout << “a++ = “ << a++ << “: ++b = “ << ++b << endl ; cout << “a = “ << a << “: b = “ << b << endl ;

return 0; }

Here is the output from the program in Listing 1: a = 20: b = 20 a++ = 20: ++b = 21 a = 21: b = 21 the notation a++ means “use the current value of a in evaluating an expression, and then increment the value of a.” while, the notation ++b means “first increment the value of b, and then use the new value in evaluating the expression. The following example illustrates this difference through the use of assignment operator ‘=’.

Listing2

#include int main( ) { int x = 5; int y = ++x; // change x, then assign to y // y is 6, x is 6 cout << “y= “ << y << “x= “ << x << endl ;

int z = 5; int y = z++; // assign to y, then change z // y is 5, z is 6 cout << “y= “ << y << “z= “ << z << endl ; return 0; }

Fig. 5 gives a concise explanation for the increment and decrement operators in prefix and post fix versions. 6- Bitwise operators

The bitwise operators operate on the bits of integer values, for example, the left-shift (<<) and right-shift (>>) operator shift bits of an integer in left and right directions respectively. The negation bitwise operator turns each 1 to a 0, and each 0 to a 1. Altogether, C++ has six such operators: <<, >>, ~, &, |, and ^.

The Shift Operators The left-shift operator has the following syntax:

value << shift

Here value is the integer value to be shifted, and shift is the number of bits to shift. For example,

13 << 3 means shift all the bits in the value 13 three places to the left. The vacated places are filled with zeros, and bits shifted past the end are discarded. Because each bit position represents a value twice that of the bit to the right, shifting one bit position is equivalent to multiplying the value by 2. Similarly, shifting two bit positions is equivalent to multiplying by 22, and shifting n positions is equivalent to multiplying by 2n. Thus, the value of 13 << 3 is 13×23, or 104.

Ex: int x = 20; int y = x << 3;

This code doesn’t change the value of x. The expression x << 3 uses the value of x to produce a new value, much as x + 3 produces a new value without altering x.

To change the value of x with the left-shift operator, the assignment operator must be used as well. x = x << 4; // regular assignment y <<= 2; // shift and assign The right-shift operator (>>), shifts bits to the right. It has the following syntax: value >> shift Value is the integer value to be shifted, and shift is the number of bits to shift. For example: 17 >> 2 means shift all the bits in the value 17 two places to the right. C++ also defines a right- shift-and-assign operator that you can use to replace the value of a variable by the shifted value: int q = 43; q >>= 2 ; // replace 43 by 43 >> 2, or 10

The Logical Bitwise Operators: These operators apply to a value on a bit-by-bit basis rather than to the whole. These operators include (~) or the complement, bitwise OR |, bitwise AND & and bitwise XOR ^. The bitwise OR operator (|) combines two integer values to produce a new integer value. Each bit in the new value is set to 1 if one or the other, or both, of the corresponding bits in the original values is set to 1. If both corresponding bits are 0, then the final bit is set to 0.

Common Bitwise Operator Techniques:

1- Turning a Bit On: The following two operations each turn on an individual bit in lottabits by ORING with the suitable value : lottabits = lottabits | set_high ; lottabits |= set_high ;

For example if it is required to set the fourth bit in lottabits variable that is currently equal to: 00 in hexadecimal i.e. (00000000), the set_high value must equal to (00001000).

2- Toggling a Bit: The following two operations each toggle a specific bit in lottabits that corresponds to a bit represented by toggle_bit value. That is, they turn the bit on if it is off, and they turn it off if it is on: lottabits = lottabits ^ toggle_bit; lottabits ^= toggle_bit; To achieve this requirement, XOR operation is used that has the property of inverting bit value from 1 0 or 0 1by XORING that bit with 1 while keeping the original values for all other bits in lottabits variable by XORING them with zeros.

3-Turning a Bit Off: also known as mask operation. To turn a specific bit off “give it a zero value” while keeping other bits with their original values an ANDING operation can be applied.

Ex: Set the seventh bit in lottabits variable to zero and maintain the other bits with no change. Assuming that lottabits is equal to “10011101”.

#include void main( ) { short lottabits = 0x9D ; short mask = 0x7F ;

cout << "lottabits = " << lottabits << endl ; // lottabits = lottabits & mask ; its can be rewritten as below lottabits &= 0x7F ; cout << hex ; cout<< "lottabits after turning 7th bit off is : "<< lottabits << endl ;

}

Recommended publications