Lec10 - Constant Variables &amp ALU, Bitwise

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 55

All

the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code.

Like we did in the previous code at the beginning of the body of the function main when we declared that a, b, and result were of type int.

variable can be either of global or local scope.

global variable is a variable declared in the main body of the source code, outside all functions.
A local variable is one declared within the body of a function or a block.

Global variables can be referred from anywhere in the code, even inside functions, whenever it is after its declaration. The scope of local variables is limited to the block enclosed in braces ({}) where they are declared.

For example, if they are declared at the beginning of the body of a function (like in function main) their scope is between its declaration point and the end of that function. In the example above, this means that if another function existed in addition to main, the local variables declared in main could not be accessed from the other function and vice versa.
4

Constant Variables & Arithmetic, logical, relational operators Bitwise operators, Left shit, right shift, OR, AND & XOR operations

C++ Data Types

Simple Integral enum Floating

address

Structured array struct union class

pointer reference

char short int long bool

signed unsigned

float double long double

char, short, int, long Different sizes of integers - different memory size Dependent upon the compiler Integer values: Sequence of one or more digits 22 129 -67 0 commas are not allowed: 100,000

Type Name
int unsigned int bool

Bytes
4 4 1

Other Names
signed unsigned none

Range of Values
2,147,483,648 to 2,147,483,647 0 to 4,294,967,295 false or true

char
signed char unsigned char short unsigned short

1
1 1 2 2

none
none none short int, signed short int unsigned short int

128 to 127
128 to 127 0 to 255 32,768 to 32,767 0 to 65,535

long
unsigned long long long

4
4 8

long int, signed long int


unsigned long int none

2,147,483,648 to 2,147,483,647
0 to 4,294,967,295 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 0 to 18,446,744,073,709,551,615

unsigned long long enum float double long double

8 varies 4 8 same as double

none none none none none


8

3.4E +/- 38 1.7E +/- 308 same as double

C++

expressions are used to express computation. Expressions include operations and the operands on which the operations are applied. Operands can be variables, literals or constants.

Precedence

controls the order of evaluation of operators.


A high precedence means an operator is evaluated (applied) before any lower precedence operators.

Operators

that have the same precedence can happen in either order, but in C++ the one on the left is evaluated first.

10

Operators () * / % + < <= > >= == != =

Precedence highest (applied first)

lowest (applied last)

11

We

can define any kind of variable as const. The compiler will check that you dont attempt to change the value of such a variable.

12

#include <iostream>

using namespace std;


int main() { const int inches_per_foot=12; const int feet_per_yard=3;

int yards=0;
int feet=0; int inches=0; cout<<Enter a length as yards, feet, and inches: ;

cin>> yards >> feet >> inches;


cout<<end1 <<Length in inches is <<inches + inches_per_foot*(feet + feet_per_yard *yards)

<<end1;
return 0; }
13

Enter a length as yards, feet, and inches :2 2 11 Length in inches is 107

14

The

compiler will complain if your code tries to modify a const variable:


const int temp = 100; temp = 21;

Error: l-value specifies const object

15

Const

tells the compiler that a variable should never be changed.


already know the variable should never be changed! - let the compiler save you from yourself (you might forget that it shouldn't be changed).

You

But

16

You

can add the const modifier to the declaration of a variable to tell the compiler that the value cannot be changed:
const double factor = 5.0/9.0; const double offset = 32.0; celcius = (fahr - offset)*factor;

17

Arithmetic

calculations

Multiplication
Division Integer division truncates remainder 7 / 5 evaluates to 1 Modulus operator returns remainder 7 % 5 evaluates to 2

18

Rules

of operator precedence

Operators in parentheses evaluated first

Nested/embedded parentheses Operators in innermost pair first Operators applied from left to right Operators applied from left to right

Multiplication, division, modulus applied next

Addition, subtraction applied last

19

Operator(s) ()

Operation(s) Parentheses

Order of evaluation (precedence) Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses on the same level (i.e., not nested), they are evaluated left to right.

*, /, or % + or -

Multiplication Division Evaluated second. If there are several, they re Modulus evaluated left to right. Addition Subtraction Evaluated last. If there are several, they are evaluated left to right.

20

if

structure

Make decision based on truth or falsity of condition

If condition met, body executed Else, body not executed

Equality

and relational operators

Equality operators
Same level of precedence Same level of precedence

Relational operators

Associate left to right


21

Sta nd a rd a lg eb ra ic eq ua lity op era tor or rela tiona l op era tor

C++ eq ua lity or rela tiona l op era tor

Exa mp le of C++ c ond ition

Mea ning of C++ c ond ition

Relational operators > <

> < >= <=

x > y x < y x >= y x <= y

x is greater than y x is less than y x is greater than or equal to y x is less than or equal to y


Equality operators =

== !=

x == y x != y

x is equal to y x is not equal to y

22

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

// code5.cpp // Using if statements, relational // operators, and equality operators. #include <iostream> using std::cout; // program uses cout using std::cin; // program uses cin using std::endl; // program uses endl // function main begins program execution int main() {

int num1; // first number to be read from user

Declare variables.

int num2; // second number to be read from user cout << "Enter two integers, and I will tell you\n"

if structurecondition is true If compares (i.e., values are values of if ( num1 == num2 ) num1 andequal), to num2 execute this if structure cout << num1 << " is equal to " << num2 << endl; If condition is true test for equality. of . are not compares statement values (i.e., values if ( num1 != num2 ) num1 andequal), execute this num2 to cout << num1 << " is not equal to " << num2 << endl; test for inequality. statement.
cin >> num1 >> num2; // read two integers
23

<< "the relationships they satisfy: ";

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

if ( num1 < num2 ) cout << num1 << " is less than " << num2 << endl;

if ( num1 > num2 ) cout << num1 << " is greater than " << num2 << endl;
if ( num1 <= num2 ) cout << num1 << " is less than or equal to " << num2 << endl; if ( num1 >= num2 ) cout << num1 << " is greater than or equal to " << num2 << endl; return 0; // indicate that program ended successfully

} // end function main

Enter two integers, and I will tell you the relationships they satisfy: 22 12 22 is not equal to 12 22 is greater than 12 22 is greater than or equal to 12

24

Enter two integers, and I will tell you the relationships they satisfy: 7 7 7 is equal to 7 7 is less than or equal to 7 7 is greater than or equal to 7

25

Common

error

Does not typically cause syntax errors

Aspects

of problem

Expressions that have a value can be used for decision

Zero = false, nonzero = true

Assignment statements produce a value (the value to be assigned)

26

Example

if ( payCode

==

4 )

cout << "You get a bonus!" << endl;

If paycode is 4, bonus given

If

== was replaced with =


if ( payCode = 4 ) cout << "You get a bonus!" << endl;

Paycode set to 4 (no matter what it was before) Statement is true (since 4 is non-zero) Bonus given in every case
27

As

their name suggests, the bitwise operators enable you to operate on an integer variable at the bit level.

Can be applied to any type of integers:


Signed Unsigned However they are usually applied to unsigned integer types.
SHIFT AND OR XOR
28

The bitwise operations are:


Provide

a means for moving bits within a register and are often used for solving alignment problems. One technique is to place the bit that fell off the right end in the hole at the left end. This is called circular shift or rotation.

2-29

2-30

Another

technique is to discard the bit that falls off the edge and always fill the hole with a 0. This is called logical shift.
that leave the sign bit unchanged are called arithmetic shifts.

Shifts

2-31

right circular shift of 3 bits on a string of 8bits is equivalent to a left circular shift of how many times?

01100101
Applying first right circular shift:

_01100101
10110010
1-32

10110010
Applying 2nd right circular shift:

_10110010 01011001
Applying 3rd right circular shift:

_ 01011001 1 0101100
1-33

Now applying left rotation to find how many Left rotations are equal to 3 right rotations 01100101
Applying first left circular shift:

0 1 1 0 0 1 0 1__ 11001010
1-34

11001010
Applying 2nd left circular shift:

1 1 0 0 1 0 1 0 __ 10010101
Applying 3rd left circular shift:

10010101_ 00101011
1-35

So

far if we compare the results of 3 right shifts and 3 left shifts they are not equal:
3 right shifts :1 0 1 0 1 1 0 0 3 left shifts: 0 0 1 0 1 0 1 1

So we shall continue applying left shifts.

1-36

Applying 4th left circular shift:

00101011_ 01010110
Applying 5th left circular shift:

01010110_

10101100

Now if we compare the results left shift is equal to right shift. Hence 5 left shits are equal to 3 right shifts.
1-37

They

shift the contents of an integer variable by a specified number of bits to the left or right.

>> operator shifts bits to the right. << operator shifts bits to the left.

Bits

that fall off either end of the variable are lost.

38

unsigned int number =163870; unsigned int result= number <<2; The left operand of the shift operator is the value to be shifted While the number of bit positions that the value is to be shifted is specified by the right operand.

Decimal 16,387 in binary :


0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1

Shift left 2:
0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0

=12
39

unsigned int number =163870; unsigned int result= number >> 2; Similarly if we apply shift right:
0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1

Shift right 2:

= 4096
40

number >> = 2;
This is equivalent to : number = number >>2 ; cout <<( number << 2);

41

As

mentioned earlier bitwise shift operators can be applied to both signed and unsigned integers. Right shift on signed integer types can vary between different systems and it depends on your compiler. In some cases it will fill 0 bits at the left to fill in the vacated bit positions. In other cases the sign bit is propagated to the right so 1 bit fills the vacated bit positions.
42

The

reason for propagating the sign bit, where this occurs, is to maintain consistency between a right shift and a divide operation. We will illustrate this with a variable of type char, just to show how it works.

43

signed char value= -104; Decimal -104 in binary :


1 0 0 1 1 0 0 0

value >> = 2;
1 1 1 0 0 1 1 0

= -26

Which is the same as dividing -104 by 4 as we would have expected.


44

Operator -

Description Bitwise complement operator. This is a unary operator that will invert the bits to its operand so 1 becomes 0 and 0 becomes 1. Bitwise AND operator which will AND the corresponding bits in its operands. If corresponding bits are both 1 then resulting bit is 1, otherwise it is 0. Bitwise exclusive OR operator (XOR) if corresponding bits are different e.g. 1 and 0 result will be 1 otherwise if bits are same e.g. 0 and 0 result will be 0. Bitwise OR operator. If corresponding bits are 0 and 0 the resulting bit will be 0, otherwise it is 1.
45

&

One

major use of AND operation is for placing 0s in one part of a bit pattern while not disturbing the other part. For example 00001111

without knowing the second operand we can say that the first four most significant bits will be 0s Moreover the four least significant bits will be a copy of the second operand.

2-46

00001111 AND 10101010 00001010

2-47

This

use of the AND operation is called masking. Here one operand, called the mask, determines which part of the other operand will affect the result. In case of AND operation, masking produces a result that is a partial replica of the one operand, with 0s occupying the nonduplicated positions.

2-48

Such

an operation is useful when manipulating a bit map,


A string of bits in which each bit represents the presence or absence of a particular object We have encountered bit maps in context of representing images, where each bit is associated with a pixel.

2-49

Where

AND operation can be used to duplicate a part of bit string while placing 0s in the nonduplicated part The OR operation can be used to duplicate a part of a string while putting 1s in the nonduplicated part For example 11110000

Produces 1s in four most significant bits While remaining bits are copied in the four least significant bits.

2-50

11110000 OR 10101010 11111010

2-51

A major use of XOR operation is in the forming of complement of a bit string XORing any byte with a mask of all 1s produces the complement of the byte.

2-52

11111111 XOR10101010 01010101

2-53

Suppose

you want to isolate the middle 4 bits of a byte by placing 0s in the other 4bits without disturbing the middle 4bits. What mask must you use together with that operation?

00000000 00111100
1-54

00111100
Apply masking with?

AND Because in AND operations we put 0s where we dont want to change the bits.
1-55

You might also like