Chapter 3 - Chapter 3 Chapter Objects types and values Bjarne Stroustrup Bjarne

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Chapter 3 Chapter Objects, types, and values Bjarne Stroustrup Bjarne Abstract Abstract Most programming tasks involve manipulating data. Most Today, we will: Today, describe how to input and output data present the notion of a variable for holding data introduce the central notions of “Type” and “Type Safety” introduce Stroustrup/Programming 2 Overview Overview Strings and string I/O Integers and integer I/O Types and objects Type safety Stroustrup/Programming 3 Input and output Input // read first name: // read #include "std_lib_facilities.h" // our course header // our int main() { cout << "Please enter your first name (followed " << "by 'enter'):\n"; string first_name; cin >> first_name; cout << "Hello, " << first_name << '\n'; } // note how several values can be output by a single statement note // a statement that introduces a variable is called a declaration // a variable holds a value of a specified type // the final return 0; is optional in main() return main() // but you may need to include it to pacify your compiler Stroustrup/Programming 4 Source files Source std_lib_facilities.h: Interfaces to libraries (declarations) Myfile.cpp: #include "std_lib_facilities.h" My code My data (definitions) "std_lib_facilities.h" is the header for our course Stroustrup/Programming 5 Input and type Input We read into a variable A variable has a type Here, first_name Here, first_name Here, string Here, string The type of a variable determines what The operations we can do on it operations Here, cin>>first_name; reads characters until a Here, cin>>first_name; whitespace character is seen whitespace White space: space, tab, newline, … Stroustrup/Programming 6 String input String // read first and second name: // read int main() { cout << "please enter your first and second names\n"; string first; string second; cin >> first >> second; // read two strings // read string name = first + ' ' + second; // concatenate strings // concatenate // separated by a space // separated cout << "Hello, "<< name << '\n'; } // I left out the #include "std_lib_facilities.h" to save space and // left // reduce distraction // // Don't forget it in real code Don't // Similarly, I left out the Windows-specific keep_window_open(); keep_window_open(); Stroustrup/Programming 7 Integers Integers // read name and age: // read int main() { cout << "please enter your first name and age\n"; string first_name; // string variable // string int age; // integer variable // integer cin >> first_name >> age; // read // read cout << "Hello, " << first_name << " age " << age << '\n'; } Stroustrup/Programming 8 Integers and Strings Integers Strings cin >> reads (until whitespace) cout << writes + concatenates += s adds the string s at end ++ is an error - is an error … Integers and floating point Integers numbers numbers cin >> reads a number cout << writes + adds += n increments by the int n ++ increments by 1 - subtracts … The type of a variable determines which operations are valid and what their meanings are for that type (that's called "overloading" or "operator overloading") Stroustrup/Programming 9 Names Names A name in a C++ program Starts with a letter, contains letters, digits, and underscores Starts (only) (only) x, number_of_elements, Fourier_transform, z2 Not names: 12x time$to$market time$to$market main line Do not start names with underscores: _foo Do _foo those are reserved for implementation and systems entities Users can't define names that are taken as keywords E.g.: int if while Stroustrup/Programming 10 Names Names Choose meaningful names Abbreviations and acronyms can confuse people Short names can be meaningful mtbf, TLA, myw, nbv when used conventionally: x is a local variable i is a loop index Don't use overly long names Ok: partial_sum element_count staple_partition Too long: the_number_of_elements remaining_free_slots_in_the_symbol_table Stroustrup/Programming 11 Simple arithmetic Simple // do a bit of very simple arithmetic: // do int main() { cout << "please enter a floating-point number: "; // prompt for a number cout prompt double n; // floating-point variable floating-point cin >> n; cout << "n == " << n << "\nn+1 == " << n+1 // '\n' means “a newline” '\n' << "\nthree times n == " << 3*n << "\ntwice n == " << n+n << "\nn squared == " << n*n << "\nhalf of n == " << n/2 << "\nsquare root of n == " << sqrt(n) // library function << library << endl; // another name for newline another } Stroustrup/Programming 12 A simple computation simple int main() // inch to cm conversion // inch { const double cm_per_inch = 2.54; // number of centimeters per inch const number int length = 1; // length in inches length while (length != 0) // length == 0 is used to exit the program while length { // a compound statement compound cout << "Please enter a length in inches: "; cin >> length; cout << length << "in. = " << cm_per_inch*length << "cm.\n"; << } } A while-statement repeatedly executes until its condition becomes false while-statement Stroustrup/Programming 13 Types and literals Types Built-in types and short and long and and and float Standard-library types string complex<Scalar> Boolean literals true false Character literals 'a', 'x', '4', '\n', '$' Integer literals 0, 1, 123, -6, 0x34, 0xa3 Floating point literals 1.2, 13.345, .3, -0.54, 1.2e3, . 3F, 1.2, .3F .3F String literals "asdf", String "asdf" "Howdy, all y'all!" "Howdy, Complex literals Floating-point types double Boolean type bool Character types char Integer types int complex<double>(12.3,99) complex<float>(1.3F) If (and only if) you need more details, see the book! Stroustrup/Programming 14 Types C++ provides a set of types E.g. bool, char, int, double int double E.g. bool Called “built-in types” C++ programmers can define new types Called “user-defined types” We'll get to that eventually The C++ standard library provides a set of types E.g. string, vector, complex E.g. string Technically, these are user-defined types they are built using only facilities available to every user they Stroustrup/Programming 15 Declaration and initialization Declaration int a = 7; a: b: int b = 9; 7 9 char c = 'a'; c: double x = 1.2; x: 1.2 string s1 = "Hello, world"; s1: 12 string s2 = "1.2"; s2: 3 Stroustrup/Programming 'a' | | "Hello, world" "1.2" 16 Objects Objects An object is some memory that can hold a value of a given type A variable is a named object A declaration names an object int a = 7; char c = 'x'; complex<double> z(1.0,2.0); string s = "qwerty"; s: a: c: z: 6 7 'x' 1.0 2.0 "qwerty" Stroustrup/Programming 17 Type safety Type Language rule: type safety Every object will be used only according to its type Ideal: static type safety A program that violates type safety will not compile A variable will be used only after it has been initialized Only operations defined for the variable's declared type will be Only applied applied Every operation defined for a variable leaves the variable with a Every valid value valid The compiler reports every violation (in an ideal system) Ideal: dynamic type safety If you write a program that violates type safety it will be If detected at run time detected Some code (typically "the run-time system") detects every Some violation not found by the compiler (in an ideal system) violation Stroustrup/Programming 18 Type safety Type Type safety is a very big deal Try very hard not to violate it “when you program, the compiler is your best friend” C++ is not (completely) statically type safe No widely-used language is (completely) statically type safe Being completely statically type safe may interfere with your ability to Being express ideas express C++ is not (completely) dynamically type safe But it won’t feel like that when it rejects code you’re sure is correct Many languages are dynamically type safe Being completely dynamically type safe may interfere with the ability to Being express ideas and often makes generated code bigger and/or slower express Most of what you’ll be taught here is type safe We’ll specifically mention anything that is not Stroustrup/Programming 19 Assignment and increment Assignment a: // changing the value of a variable // changing int a = 7; // a variable of type int called a int variable called // initialized to the integer value 7 initialized a = 9; // assignment: now change a''s value to 9 s 7 9 a = a+a; a+a; // assignment: now double a's value assignment: value 18 a += 2; += // increment a's value by 2 20 ++a; // increment a's value (by 1) 21 Stroustrup/Programming 20 A type-safety violation type-safety (“implicit narrowing”) // Beware: C++ does not prevent you from trying to put a large value // Beware: // into a small variable (though a compiler may warn) // into int main() { 20000 a int a = 20000; char c = a; ??? c: int b = c; if (a != b) // != means “not equal” means cout << "oops!: " << a << "!=" << b << '\n'; else cout << "Wow! We have large characters\n"; } Try it to see what value b gets on your machine gets Stroustrup/Programming 21 A type-safety violation (Uninitialized variables) (Uninitialized // Beware: C++ does not prevent you from trying to use a variable // Beware: // before you have initialized it (though a compiler typically warns) // before int main() { int x; char c; char double d; double // x gets a “random” initial value // gets // c gets a “random” initial value gets // d gets a “random” initial value gets // – not every bit pattern is a valid floating-point value not double dd = d; // potential error: some implementations // potential // can’t copy invalid floating-point values can’t cout << " x: " << x << " c: " << c << " d: " << d << '\n'; } Always initialize your variables – beware: “debug mode” may initialize Always (valid exception to this rule: input variable) (valid Stroustrup/Programming 22 A technical detail technical In memory, everything is just bits; type is what gives meaning In to the bits to (bits/binary) 01100001 is the int 97 is the char 'a' (bits/binary) is is (bits/binary) 01000001 is the int 65 is the char 'A' (bits/binary) is is (bits/binary) 00110000 is the int 48 is the char '0' is is char c = 'a'; cout << c; // print the value of character c, which is a // which int i = c; cout << i; // print the integer value of the character c, which is 97 // print 97 This is just as in “the real world”: What does “42” mean? You don’t know until you know the unit used know Meters? Feet? Degrees Celsius? $s? a street number? Height in inches? … Stroustrup/Programming 23 About Efficiency About C++ is derived from C, which is a systems programming language C++’s built-in types map directly to computer main memory C++’s built-in operations map directly to machine instructions An integer + is implemented by an integer add operation An integer = is implemented by a simple copy operation C++ provides direct access to most of the facilities provided by modern C++ hardware C++ help users build safer, more elegant, and efficient new types C++ and operations using built-in types and operations. and a char is stored in a byte char An int is stored in a word An int A double fits in a floating-point register double E.g., string E.g., string Eventually, we’ll show some of how that’s done For now, don’t worry about “efficiency” Concentrate on correctness and simplicity of code Stroustrup/Programming 24 A bit of philosophy bit One of the ways that programming resembles other kinds of One engineering is that it involves tradeoffs. engineering You must have ideals, but they often conflict, so you must You decide what really matters for a given program. decide Type safety Run-time performance Ability to run on a given platform Ability to run on multiple platforms with same results Compatibility with other code and systems Ease of construction Ease of maintenance Don't skimp on correctness or testing By default, aim for type safety and portability Stroustrup/Programming 25 Another simple computation Another // inch to cm and cm to inch conversion: // inch int main() { const double cm_per_inch = 2.54; int val; char unit; while (cin >> val >> unit) { // keep reading // if (unit == 'i') // 'i' for inch if // for cout << val << "in == " << val*cm_per_inch << "cm\n"; else if (unit == 'c') // 'c' for cm // for cout << val << "cm == " << val/cm_per_inch << "in\n"; else return 0; // terminate on a “bad unit”, e.g. 'q' // } } Stroustrup/Programming 26 The next lecture The Will talk about expressions, statements, Will debugging, simple error handling, and simple rules for program construction rules Stroustrup/Programming 27 ...
View Full Document

This note was uploaded on 02/18/2012 for the course CSCE 121 taught by Professor Walter daugherity during the Fall '09 term at Texas A&M.

Ask a homework question - tutors are online