objects types, variables, and constants 1 chapter 3

30
Objects Objects Types, Variables, and Constants 1 Chapter 3

Upload: lambert-nicholson

Post on 14-Dec-2015

225 views

Category:

Documents


0 download

TRANSCRIPT

ObjectsObjects

Types, Variables, and Constants

1

Chapter 3

Overview of C++ Overview of C++ StatementsStatements

2

C++ Statements

Declarations; Expressions; Other

ObjectsOperations

ExpressionsExpressionsIn a C++ program, any finite sequence of objects and operations that combine to produce a value is called an expression.

Examples from our temperature problem:

1.8 * celsius

1.8 * celsius + 32

3

Even:

1.8;32;"Hello";1 + 1;;;;;

We focus now on C++ We focus now on C++ objectsobjects and will look at operations and will look at operations later.later.

1.8

fahrenheit = 1.8 * celsius + 32

Aside #1: expression; is a statement.)Aside #2: expressions may be empty

Object CategoriesObject Categories

There are three kinds of objects:

Literals: unnamed objects having a value (0, -3, 2.5, 2.998e8, 'A', "Hello\n", ...)

Variables: named objects whose values can change during program execution

Constants: named objects whose values cannot change during program execution

4

See Footnoteon p. 48

Study§3.2

Have memory

allocated to them

LiteralsLiterals

– int literals are integers: literals are integers: -27, 0, 4, +4

or E

– There are just two bool literals: false, true

5

Enclose in '

Enclose in "

– char literals are single characters:'A', 'a', '9', '$', '?', ...

– string literals are sequences of characters:

"Hello", "Goodbye", "Goodbye\n"

5 basic types

– double literals are real numbers, and can literals are real numbers, and can be:be:

fixed-point: fixed-point: -0.333, 0.5, 1.414, ..., ...

floating-point: floating-point: 2.998e8, 0.2998e9, ..., ...

Not inter-changeable

Some Variations: unsigned, long, short

Variations: float, long double

Variable DeclarationsVariable Declarations

Examples:Examples:int idNumber;int age = 18;

double celsius, kelvin = 0;cin >> celsius;double fahrenheit = 1.8 * celsius + 32;

char letterGrade = 'A';

bool ok, done = false;

6

Declare only once

Variables are used to store values, and can be Variables are used to store values, and can be either either uninitializeduninitialized or or initializedinitialized. They must be . They must be declaredbefore they are used.before they are used.

Pattern: Pattern: type name;type name = expression;

Allocates a memory location for values of this type and associates its address with name

Not adeclaration

Assignment StatementsAssignment Statements

Examples:Examples:age = 19;

celsius = 1.1 * celsius;

letterGrade = 'B';

done = true;

7

Pattern: Pattern: name = expression;

The value of a variable can be changed The value of a variable can be changed during execution by an assignment during execution by an assignment statement.statement.

Changes value in name's memory location to value of expression

Constant DeclarationsConstant Declarations

const char MIDDLE_INITIAL = 'A';

const string PROMPT = "Enter a number: ";

8

Pattern:Pattern: const type NAME = expression;

Constants are used to represent a value Constants are used to represent a value with a meaningful name, and with a meaningful name, and must be must be initializedinitialized. They cannot be changed later.. They cannot be changed later.

Could use in

Proj. 1.3

Examples:Examples:const int MAX_SCORE = 100;

const double PI = 3.14159265359;

Allocates a memory location for values of this type, associates its address with NAME, puts value of expression in it, and locks it.

IdentifiersIdentifiers

The name of an object is called an The name of an object is called an identifier (because it identifies the (because it identifies the object).object).

C++ identifiers must begin with a letter C++ identifiers must begin with a letter (underscores are permitted, but (underscores are permitted, but discouraged) followed by zero or more discouraged) followed by zero or more letters, digits or underscores.letters, digits or underscores.

Valid: Valid: age, r2d2, myGPA, MAX_SCORE,...,...

Invalid: Invalid: 123go, coffee-time, sam's, $name,...,...9

May not be C++keywords

(See Appendix B)

Seeslide 24

ConventionsConventions

We will use the following commonly-usedWe will use the following commonly-usedconvention to keep variable and constantconvention to keep variable and constantobjects distinct. objects distinct.

• Constant names: all uppercase, with Constant names: all uppercase, with multiple words separated by underscores multiple words separated by underscores (e.g., (e.g., MAX_SCORE))

• Variable names: all lowercase, but the first Variable names: all lowercase, but the first letter of each word after the first letter of each word after the first capitalizedcapitalized(e.g., (e.g., lastName))

10

Use meaningful identifiers

for readability!

“camelback” notation

Represented in memory by a code.– ASCII uses 8 bits (1 byte) to represent a

character, allowing for 28 = 256 different characters.

char Objects Objects

'a' = 97 = 01100001'0' = 48 = 00110000 11

p. 61App. A

Java

chars can be treated as small integers; e.g,. char ch1 = 'A', ch2; int x = 2*ch1 + 1; ch2 = ch1 + 1; cout << x << ' ' << ch2 << '\n';Output? 131 B

0100000165 =

Most Most commonly used used code is ASCII:code is ASCII:

'A' =

– Unicode's first version used 16 bits to represent a character, allowing for 216 = 65,536 different characters. Now, 16, 24, or 32 bits.

See OtherCourse Information class page

Escape CharactersEscape Characters

C++ provides a number of C++ provides a number of escape characters::

12

'\n' newline character'\t' horizontal tab'\v' vertical tab'\f' form feed'\a' alert/bell'\\' backslash char'\'' apostrophe'\"' double quote'\ooo' char with octal code ooo'\xhhh' char with hex code hhh

See Appendix A

int Objects ObjectsThree forms:Three forms:

– decimaldecimal (base-10): (base-10): 0 or begin with a begin with a nonzero digit or sign (-45, -2, 0, +21, 36, 65536, ...)digit or sign (-45, -2, 0, +21, 36, 65536, ...)

– octaloctal (base-8): begin with a (base-8): begin with a 0 followed by followed by octal digits (01, 02, 03, 04, 05, 06, 07, digits (01, 02, 03, 04, 05, 06, 07,

010 , 011 , 012, ..., 017, 020, 021, …)

0xa, 0xb, 0xc, 0xd, 0xe, 0xf,0x10, 0x11, ...)

– hexadecimalhexadecimal (base-16): begin with (base-16): begin with 0x followed by digits with a, b, c, d, e, f = 10, followed by digits with a, b, c, d, e, f = 10, 11, 12, 13, 14, 15 (0x1, 0x2, ..., 0x7, 0x8, 11, 12, 13, 14, 15 (0x1, 0x2, ..., 0x7, 0x8, 0x9,0x9,

13

See second item on OtherCourse Information class page

unsigned Objects Objects

For objects whose values are never negative, C++ provides the unsigned type.

They also may be expressed in decimal, octal, and hexadecimal forms.

The major advantage of using unsigned instead of int when values being processed are known to be nonnegative is that larger values can be stored.

14

Ranges of Integer ValuesRanges of Integer Values

Using 32 bits, int values range from -231 (-2147483648) to 231-1 (2147483647); unsigned values range from 0 to 232-1 (4294967295).

An int value "loses" one of its bits to the sign, and so the maximum int value is about half of the maximum unsigned value.

15

INT_MIN

<climits> defines INT_MIN, INT_MAX,UINT_MAX, and other constants that specifyranges of C++ integers; <cfloat> does thisfor C++ real values. (See App. D)

UINT_MAX

INT_MAX

16

//-- Program to demonstrate the effects of overflow #include <iostream> using namespace std; int main() { int number = 2; for (int i = 1; i <= 15; i = i + 1) { cout << number << '\n'; number = 10 * number; } }

Output:

2202002000200002000002000000200000002000000002000000000-1474836480-1863462912-1454759936-1662697472552894464

Strange Behavior of Integer Overflow

overflowoverflow

Overflow: when a value gets out of range; for example, an integer exceeds INT_MAX = 231 - 1 = 2147483647.

17

//-- Program to demonstrate the modular "wrap-around" effect of overflow

#include <iostream>#include <climits>using namespace std;

int main(){ int number = INT_MAX - 3;

for (int i = 1; i <= 7; i = i + 1) { cout << number << '\n'; number = number + 1; }}

Output:

2147483644214748364521474836462147483647-2147483648-2147483647-2147483646

Why this strange behavior?

Check INT_MAX + 1,INT_MAX + 2, . . .

INT_MAXINT_MIN

Arithmetic is modular

INT_MIN . . . INT_MAX

int Representation Representation

Integers are often represented internally in theIntegers are often represented internally in thetwos-complement format, where the high- format, where the high-order (leftmost) bit indicates the number’s sign:order (leftmost) bit indicates the number’s sign:

210 = 00000000000000102

110 = 00000000000000012

010 = 00000000000000002

-110 = 11111111111111112

-210 = 11111111111111102

Here we show 16 bits, but 32 or 64 are more common.

18

Sec. 3.3

Two's-ComplementTwo's-Complement

To find twos-complement representation of To find twos-complement representation of a a negativenegative number (e.g., -12): number (e.g., -12):

Represent its absolute value in binary:Represent its absolute value in binary:

((00000000000011000000000000001100))

Invert (complement) the bits:Invert (complement) the bits:

((11111111111100111111111111110011))

Add 1 Add 1

19

((11111111111101001111111111110100))Simpler: Flip all bits Simpler: Flip all bits to the left of to the left of rightmost 1.rightmost 1.

Stop here for nonnegative

numbersTry

practiceexercises

— Week 3of schedule

20

+ 0 1 0 0 1

1 1 10

* 0 1 0 0 0 1 0 1

5 + 7:

0000000000000101

+0000000000000111

5 + –6: 0000000000000101 +1111111111111010

0000000000001100

111 carry bits

1111111111111111

Why Use Two's Complement?Why Use Two's Complement?

Because usual algorithms for +, * work!

double Objects Objects

= 1.01112 22

0 1000000000101110000000000000000000000000000000000000000000000000

sign(1 bit)

mantissa(52 bits)

exponent

(11 bits)

21

1023

Real values are often represented in 64 bits using the IEEE floating point standard:

5.75 = 101.112

See Ch. 3,pp. 59-61

float (single precision):bias = 127; exponent: 8 bitsmantissa: 23 bits

Trypractice

exerciseson course schedule

"bias"+

22

//-- Effect of roundoff error

#include <iostream>#include <cmath>using namespace std;

int main(){ for (double x = 0; x != 50.0; x = x + 0.1) { doouble y = x * sqrt(1 + sin(x)); cout << x << " " << y << '\n'; //if (x > 60) break; }}

Execution:0 00.1 0.1048730.2 0.218968 . . .22.6 14.785922.7001 13.410322.8001 11.9884 . . .49.9998 42.93750.0998 45.782650.1998 48.5246 . . .100.099 76.3241 . . .

So they can't be stored exactly; error in this representation is called roundoff error.

Patriot missile failureSee Other Course Information

Problem: Binary representations of most real numbers do not terminate; e.g., 13.1 = 1101.00011001100110011…

23

/* temperature.cpp converts a Celsius temperature to Fahrenheit. John Doe Lab 1 Jan. 6, 2011 CPSC 104X Input: A Celsius temperature Output: Corresponding Fahrenheit temperature-----------------------------------------------*/

#include <iostream> // cin, cout, <<, >>using namespace std;

int main(){ cout << "John Doe CPSC 104X -- Lab 1\n\n"; cout << "** Convert Celsius temps to Fahrenheit **\n"; cout << "Please enter a temperature in Celsius: "; double celsius; cin >> celsius; double fahrenheit = 1.8 * celsius + 32; cout << celsius << " degrees Celsius is " << fahrenheit << " degrees Fahrenheit.\n";}

24

The name of the song is called "Haddocks' Eyes"."Oh, that's the name of the song, is it?" Alice said, trying to feel interested."No, you don't understand," the Knight said, looking a little vexed."That's what the name is called. The name really is 'The Aged Aged Man'."'Then I ought to have said, "That's what the song is called"?' Alice corrected herself."No, you oughtn't: that's quite another thing! The song is called 'Ways and Means': but that's only what it's called, you know!""Well, what is the song, then?" said Alice, who was by this time completely bewildered."I was coming to that," the Knight said. "The song really is 'A-Sitting On a Gate': and the tune's my own invention."

•Lewis Carroll, Through The Looking Glass

The name of the student's letter grade is called "letterGrade.""Oh, that's the name of the student's letter grade, is it?" Alice said, trying to feel interested."No, you don't understand," the Knight said, looking a little vexed."That's what the name is called. The name really is 0x123abc, a memory location that stores the student's letter grade."'Then I ought to have said, "The student's letter grade is 0x123abc"? Alice corrected herself."No, you oughtn't: that's quite another thing! The student's letter grade is called 'A': but that's only what it's called, you know!""Well, what is the letter grade, then?" said Alice, who was by this time completely bewildered."I was coming to that," the Knight said. "The student's letter grade really is 10000001 and it's my own initialization."

A

int age: 0xbfe0b82cint idNumber: 0xbfe0b828int x: 0xbfe0b824int y: 0xbfe0b820double celsius: 0xbfe0b818double kelvin: 0xbfe0b810double fahrenheit: 0xbfe0b808char letterGrade: 0xbfe0b807char a: 0xbfe0b806char b: 0xbfe0b805char c: 0xbfe0b804bool ok: 0xbfe0b803bool done: 0xbfe0b802bool d: 0xbfe0b801bool e: 0xbfe0b800

int age = 18; int idNumber, x, y;

double celsius = 0, kelvin = 0; double fahrenheit = 1.8 * celsius + 32;

char letterGrade = 'A', a, b, c; bool ok, done = false, d, e;

int age: 0012FF60int idNumber: 0012FF54int x: 0012FF48int y: 0012FF3Cdouble celsius: 0012FF2Cdouble kelvin: 0012FF1Cdouble fahrenheit: 0012FF0Cchar letterGrade: 0012FF03char a: 0012FEF7char b: 0012FEEBchar c: 0012FEDFbool ok: 0012FED3bool done: 0012FEC7bool d: 0012FEBBbool e: 0012FEAFPress any key to continue . . .

Unix/Linux Visual C++

B

Enter character (* to stop): A01000001

Enter character (* to stop): B01000010

Enter character (* to stop): C01000011

Enter character (* to stop): Z01011010

Enter character (* to stop): a01100001

Enter character (* to stop): ;00111011

Enter character (* to stop): @01000000

Enter character (* to stop): *

C

Enter number (-999 to stop): 100000000000000000000000000000001

Enter number (-999 to stop): 200000000000000000000000000000010

Enter number (-999 to stop): 300000000000000000000000000000011

Enter number (-999 to stop): 102400000000000000000000010000000000

Enter number (-999 to stop): -111111111111111111111111111111111

Enter number (-999 to stop): -211111111111111111111111111111110

Enter number (-999 to stop): -311111111111111111111111111111101

Enter number (-999 to stop): -999

D

Enter number (-99 to stop): 5.7501000000101110000000000000000000

Enter number (-99 to stop): 100111111100000000000000000000000

Enter number (-99 to stop): .2500111110100000000000000000000000

Enter number (-99 to stop): -.2510111110100000000000000000000000

Enter number (-99 to stop): 13.101000001010100011001100110011010

Enter number (-99 to stop): -.110111101110011001100110011001101

Enter number (-99 to stop): .300111110100110011001100110011010

Enter number (-99 to stop): -99

E

#include <iostream>#include <climits>#include <cfloat>using namespace std;

int main(){ cout << "INT_MAX = " << INT_MAX << endl << "INT_MIN = " << INT_MIN << endl << "UINT_MAX = " << UINT_MAX << endl << "SHRT_MAX = " << SHRT_MAX << endl << "SHRT_MIN = " << SHRT_MIN << endl << "LONG_MAX = " << LONG_MAX << endl << "LONG_MIN = " << LONG_MIN << endl << "CHAR_MAX = " << CHAR_MAX << endl << "CHAR_MIN = " << CHAR_MIN << endl << "FLT_MAX = " << FLT_MAX << endl << "FLT_MIN = " << FLT_MIN << endl << "DBL_MAX = " << DBL_MAX << endl << "DBL_MIN = " << DBL_MIN << endl << "LDBL_MAX = " << LDBL_MAX << endl << "LDBL_MIN = " << LDBL_MIN << endl << "FLT_EPSILON = " << FLT_EPSILON << endl << "DBL_EPSILON = " << DBL_EPSILON << endl << "LDBL_EPSILON = " << LDBL_EPSILON << endl;}

INT_MAX = 2147483647INT_MIN = -2147483648UINT_MAX = 4294967295SHRT_MAX = 32767SHRT_MIN = -32768LONG_MAX = 2147483647LONG_MIN = -2147483648CHAR_MAX = 127CHAR_MIN = -128FLT_MAX = 3.40282e+038FLT_MIN = 1.17549e-038DBL_MAX = 1.79769e+308DBL_MIN = 2.22507e-308LDBL_MAX = 1.79769e+308LDBL_MIN = 2.22507e-308FLT_EPSILON = 1.19209e-007DBL_EPSILON = 2.22045e-016LDBL_EPSILON = 2.22045e-016

F

#include <iostream>#include <cmath>using namespace std;

int main(){ for (double x = 0; x != 50.0; x = x + .01) { double y = x * sqrt(1 + sin(x)); cout << x << " " << y << endl; }}

4.37001 1.052834.38001 1.0247 . . .49.9576 41.707349.9676 42.000349.9776 42.292349.9876 42.583449.9976 42.8735

0 00.01 0.01004990.02 0.0201990.03 0.03044660.04 0.04079190.05 0.05123420.06 0.06177270.07 0.07240660.08 0.08313520.09 0.09395750.1 0.1048730.11 0.1158810.12 0.12698 . . .4.33 1.163664.34 1.13624.35 1.108584.36 1.08078

50.0076 43.162750.0176 43.450950.0276 43.738150.0376 44.024450.0476 44.309650.0576 44.593950.0676 44.8772 . . .