Chapter 3 Objects, types, and values Bjarne Stroustrup www.stroustrup.com/Programming.

Slides:



Advertisements
Similar presentations
Chapter 10 Input/Output Streams
Advertisements

Lecture Computer Science I - Martin Hardwick Strings #include using namespace std; int main () { string word; cout
Chapter 11 Customizing I/O Bjarne Stroustrup
Chapter 21 The STL (maps and algorithms) Bjarne Stroustrup
Chapter 8 Technicalities: Functions, etc. Bjarne Stroustrup
Chapter 7 Completing a Program
Review for Final Exam Chapters 1–20 (Programming and C++ in 75 minutes) Bjarne Stroustrup Ronnie Ward 1Stroustrup/PPP -
Chapter 4 Computation Bjarne Stroustrup
Chapter 9 Technicalities: Classes, etc. Bjarne Stroustrup
Introduction to Programming Overview of Week 2 25 January Ping Brennan
C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables.
This Time Whitespace and Input/Output revisited The Programming cycle Boolean Operators The “if” control structure LAB –Write a program that takes an integer.
Starting Out with C++, 3 rd Edition 1 Chapter 10 – Characters, Strings, and the string Class.
Chapter 20 The STL (containers, iterators, and algorithms) John Keyser’s Modifications of Slides by Bjarne Stroustrup
Introduction to Programming Lecture 15. In Today’s Lecture Pointers and Arrays Manipulations Pointers and Arrays Manipulations Pointers Expression Pointers.
Chapter 17 vector and Free Store John Keyser’s Modifications of Slides By Bjarne Stroustrup
1 Chapter 11 Introducing the Class Pages ( )
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 5 Functions for All Subtasks.
Strings.
C++ Basics March 10th. A C++ program //if necessary include headers //#include void main() { //variable declaration //read values input from user //computation.
AU/MITM/1.6 By Mohammed A. Saleh 1. Introducing the string Class  Instead of using a character array to hold a string, you can use a type string variable.
Chapter 3. Expressions and Interactivity CSC125 Introduction to C++
What have we learned so far… Preprocessor directives Introduction to C++ Variable Declaration Display Messages on Screen Get Information from User Performed.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 3 Objects, Types, and Values Hartmut Kaiser
1 Objectives Understand streamed input and output.
Input/Output Main Memory istream ostream Disk Drive Keyboard Scanner Disk Drive Monitor Printer stream = sequence of bytes.
1 September 6, 2005CS150 Introduction to Computer Science I What Actions Do We Have Part 1 CS150 Introduction to Computer Science I.
Working with the data type: char  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming.
1 CIS Jan Overview Evolution of C++ Programming Style Syntax & Semantics Comments & White Space Data Types Variables & Declarations cout.
UNFORMATTED INPUT OUTPUT. Topics to be discussed……………….. overloaded operators >> and and
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
Programming Languages
Chapter 3 Getting Started with C++
Chapter 02 (Part III) Introduction to C++ Programming.
CHAPTER 7 DATA INPUT OUTPUT Prepared by: Lec. Ghader R. Kurdi.
Chapter 3 Objects, types, and values Bjarne Stroustrup
Chapter 0 Getting Started. Objectives Understand the basic structure of a C++ program including: – Comments – Preprocessor instructions – Main function.
Input/Output Sujana Jyothi C++ Workshop Day 2. C++ I/O Basics 2 I/O - Input/Output is one of the first aspects of programming that needs to be mastered:
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
Operating System Using setw and setprecision functions Using setiosflags function Using cin function Programming 1 DCT
Road map char data type Reading –Liang 5: Chapter 2: 2.7.4; 2.9; –Liang 6: Chapter 2: 2.7.4; 2.9 –Liang 7: Chapter 2: 2.7.4; 2.9.
Chapter 15 Strings as Character Arrays
An Array Type For Strings. Two ways to represent strings – i.e. “Hello” cstring An array with base type char Older way of processing strings Null character.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
More about strings in C++. String member functions The next three slides present information about functions that are members of the C++ string class.
CSCI 130 More on Arrays. Multi-dimensional Arrays Multi - Dimensional arrays: –have more than one subscript –can be directly initialized –can be initialized.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
1 Structure of Simple C++ Program Chapter 1 09/09/13.
Week 13 - Friday.  What did we talk about last time?  Server communications on a socket  Function pointers.
String in C++. 2 Using Strings in C++ Programs String library or provides functions to: - manipulate strings - compare strings - search strings ASCII.
Lecture 2 Variables, Types, Operators Sampath Jayarathna Cal Poly Pomona Based on slides created by Bjarne Stroustrup & Tony Gaddis CS 128 Introduction.
Lecture 3 Expressions, Type Conversion, Math and String
Introduction to C++ Introduced by Bjarne Stroustrup of AT&T’s Bell Laboratories in mid-1980’s Based on C C++ extended C to support object-oriented programming.
Chapter 3: Expressions and Interactivity.
getline() function with companion ignore()
C++ fundamentals Lecture 1, Chapter 2 – pp /22/2018 Y K Choi.
Manipulators CSCE 121 J. Michael Moore
Basic Input and Output C++ programs can read and write information using streams A simple input stream accepts typed data from a keyboard A simple output.
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Introduction to C++ Introduced by Bjarne Stroustrup of AT&T’s Bell Laboratories in mid-1980’s Based on C C++ extended C to support object-oriented programming.
Chapter 3 Input output.
Transp Course 2014 Overview.
Introduction to C++ Programming
Lecture 2 Variables, Types, Operators
Chapter 3 Objects, types, and values
Appendix B.1 Lex Appendix B.1 -- Lex.
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Lecture 3 Expressions, Type Conversion, and string
getline() function with companion ignore()
Lex Appendix B.1 -- Lex.
Presentation transcript:

Chapter 3 Objects, types, and values Bjarne Stroustrup

Abstract Most programming tasks involve manipulating data. Today, we will: Most programming tasks involve manipulating data. Today, we will: describe how to input and output data describe how to input and output data present the notion of a variable for holding data present the notion of a variable for holding data introduce the central notions of Type and Type Safety introduce the central notions of Type and Type Safety 2Stroustrup/Programming

Overview Strings and string I/O Strings and string I/O Integers and integer I/O Integers and integer I/O Types and objects Types and objects Type safety Type safety 3Stroustrup/Programming

Input and output // read first name: #include "std_lib_facilities.h"// our course header 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 // 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() // but you may need to include it to pacify your compiler 4Stroustrup/Programming

Source files "std_lib_facilities.h" is the header for our course "std_lib_facilities.h" is the header for our course 5 Interfaces to libraries (declarations) #include "std_lib_facilities.h" My code My data (definitions) Myfile.cpp: std_lib_facilities.h: Stroustrup/Programming

Input and type We read into a variable We read into a variable Here, first_name Here, first_name A variable has a type A variable has a type Here, string Here, string The type of a variable determines what operations we can do on it The type of a variable determines what operations we can do on it Here, cin>>first_name; reads characters until a whitespace character is seen Here, cin>>first_name; reads characters until a whitespace character is seen White space: space, tab, newline, … White space: space, tab, newline, … 6Stroustrup/Programming

String input // read first and second name: int main() { cout << "please enter your first and second names\n"; string first; string second; cin >> first >> second;// read two strings string name = first + ' ' + second;// concatenate strings // separated by a space cout << "Hello, "<< name << '\n'; } // I left out the #include "std_lib_facilities.h" to save space and // reduce distraction // Don't forget it in real code // Similarly, I left out the Windows-specific keep_window_open(); 7Stroustrup/Programming

Integers // read name and age: int main() { cout << "please enter your first name and age\n"; string first_name;// string variable int age;// integer variable cin >> first_name >> age;// read cout << "Hello, " << first_name << " age " << age << '\n'; } 8Stroustrup/Programming

Integers and Strings Strings Strings cin >> reads (until whitespace) cin >> reads (until whitespace) cout << writes cout << writes + concatenates + concatenates += s adds the string s at end += s adds the string s at end ++ is an error ++ is an error - is an error - is an error … Integers and floating point numbers Integers and floating point numbers cin >> reads a number cout << writes + adds += n increments by the int n ++ increments by 1 - subtracts … 9 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

Names A name in a C++ program A name in a C++ program Starts with a letter, contains letters, digits, and underscores (only) Starts with a letter, contains letters, digits, and underscores (only) x, number_of_elements, Fourier_transform, z2 x, number_of_elements, Fourier_transform, z2 Not names: Not names: 12x 12x time$to$market time$to$market main line main line Do not start names with underscores: _foo Do not start names with underscores: _foo those are reserved for implementation and systems entities those are reserved for implementation and systems entities Users can't define names that are taken as keywords Users can't define names that are taken as keywords E.g.: E.g.: int int if if while while double double 10Stroustrup/Programming

Names Choose meaningful names Choose meaningful names Abbreviations and acronyms can confuse people Abbreviations and acronyms can confuse people mtbf, TLA, myw, nbv mtbf, TLA, myw, nbv Short names can be meaningful Short names can be meaningful when used conventionally: when used conventionally: x is a local variable x is a local variable i is a loop index i is a loop index Don't use overly long names Don't use overly long names Ok: Ok: partial_sum element_count staple_partition partial_sum element_count staple_partition Too long: Too long: the_number_of_elements remaining_free_slots_in_the_symbol_table the_number_of_elements remaining_free_slots_in_the_symbol_table 11Stroustrup/Programming

Simple arithmetic // do a bit of very simple arithmetic: int main() { cout << "please enter a floating-point number: "; // prompt for a number double n; // floating-point variable cin >> n; cout << "n == " << n << "\nn+1 == " << n+1 // '\n' means a newline << "\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 << endl; // another name for newline } 12Stroustrup/Programming

A simple computation int main()// inch to cm conversion { const double cm_per_inch = 2.54; // number of centimeters per inch int length = 1; // length in inches while (length != 0) // length == 0 is used to exit the program { // a compound statement (a block) cout << "Please enter a length in inches: "; cin >> length; cout << length << "in. = " << cm_per_inch*length << "cm.\n"; << cm_per_inch*length << "cm.\n";}} A while-statement repeatedly executes until its condition becomes false A while-statement repeatedly executes until its condition becomes false 13Stroustrup/Programming

Types and literals Built-in types Built-in types Boolean type Boolean type bool bool Character types Character types char char Integer types Integer types int int and short and long and short and long Floating-point types Floating-point types double double and float and float Standard-library types Standard-library types string string complex complex Boolean literals Boolean literals true false Character literals Character literals 'a', 'x', '4', '\n', '$' Integer literals Integer literals 0, 1, 123, -6, 0x34, 0xa3 Floating point literals Floating point literals 1.2, ,.3, -0.54, 1.2e3,. 3F,.3F String literals "asdf", String literals "asdf", "Howdy, all y'all! Complex literals Complex literals complex (12.3,99) complex (1.3F) 14 If (and only if) you need more details, see the book! Stroustrup/Programming

Types C++ provides a set of types C++ provides a set of types E.g. bool, char, int, double E.g. bool, char, int, double Called built-in types Called built-in types C++ programmers can define new types C++ programmers can define new types Called user-defined types Called user-defined types We'll get to that eventually We'll get to that eventually The C++ standard library provides a set of types The C++ standard library provides a set of types E.g. string, vector, complex E.g. string, vector, complex Technically, these are user-defined types Technically, these are user-defined types they are built using only facilities available to every user they are built using only facilities available to every user 15Stroustrup/Programming

Declaration and initialization int a = 7; int b = 9; char c = 'a'; double x = 1.2; string s1 = "Hello, world"; string s2 = "1.2"; 'a' | "Hello, world" 3 | "1.2" a: b: c: x: s1: s2: Stroustrup/Programming

Objects An object is some memory that can hold a value of a given type An object is some memory that can hold a value of a given type A variable is a named object A variable is a named object A declaration names an object A declaration names an object int a = 7; char c = 'x'; complex z(1.0,2.0); string s = "qwerty"; 17 7 'x' 1.0 "qwerty" a: s: c: z: Stroustrup/Programming

Type safety Language rule: type safety Language rule: type safety Every object will be used only according to its type Every object will be used only according to its type A variable will be used only after it has been initialized A variable will be used only after it has been initialized Only operations defined for the variable's declared type will be applied Only operations defined for the variable's declared type will be applied Every operation defined for a variable leaves the variable with a valid value Every operation defined for a variable leaves the variable with a valid value Ideal: static type safety Ideal: static type safety A program that violates type safety will not compile A program that violates type safety will not compile The compiler reports every violation (in an ideal system) The compiler reports every violation (in an ideal system) Ideal: dynamic type safety Ideal: dynamic type safety If you write a program that violates type safety it will be detected at run time If you write a program that violates type safety it will be detected at run time Some code (typically "the run-time system") detects every violation not found by the compiler (in an ideal system) Some code (typically "the run-time system") detects every violation not found by the compiler (in an ideal system) 18Stroustrup/Programming

Type safety Type safety is a very big deal Type safety is a very big deal Try very hard not to violate it Try very hard not to violate it when you program, the compiler is your best friend when you program, the compiler is your best friend But it wont feel like that when it rejects code youre sure is correct But it wont feel like that when it rejects code youre sure is correct C++ is not (completely) statically type safe C++ is not (completely) statically type safe No widely-used language is (completely) statically type safe No widely-used language is (completely) statically type safe Being completely statically type safe may interfere with your ability to express ideas Being completely statically type safe may interfere with your ability to express ideas C++ is not (completely) dynamically type safe C++ is not (completely) dynamically type safe Many languages are dynamically type safe Many languages are dynamically type safe Being completely dynamically type safe may interfere with the ability to express ideas and often makes generated code bigger and/or slower Being completely dynamically type safe may interfere with the ability to express ideas and often makes generated code bigger and/or slower Most of what youll be taught here is type safe Most of what youll be taught here is type safe Well specifically mention anything that is not Well specifically mention anything that is not 19Stroustrup/Programming

Assignment and increment // changing the value of a variable int a = 7; // a variable of type int called a // initialized to the integer value 7 // initialized to the integer value 7 a = 9; // assignment: now change a's value to 9 a = a+a; // assignment: now double a's value a += 2; // increment a's value by 2 ++a; // increment a's value (by 1) a: Stroustrup/Programming

A type-safety violation (implicit narrowing) // Beware: C++ does not prevent you from trying to put a large value // into a small variable (though a compiler may warn) int main() { int a = 20000; char c = a; int b = c; if (a != b) // != means not equal cout << "oops!: " << a << "!=" << b << '\n'; else cout << "Wow! We have large characters\n"; } Try it to see what value b gets on your machine Try it to see what value b gets on your machine a ??? c: Stroustrup/Programming

A type-safety violation (Uninitialized variables) // Beware: C++ does not prevent you from trying to use a variable // before you have initialized it (though a compiler typically warns) int main() { int x;// x gets a random initial value char c; // c gets a random initial value double d; // d gets a random initial value // – not every bit pattern is a valid floating-point value double dd = d;// potential error: some implementations // cant copy invalid floating-point values cout << " x: " << x << " c: " << c << " d: " << d << '\n'; } Always initialize your variables – beware: debug mode may initialize (valid exception to this rule: input variable) Always initialize your variables – beware: debug mode may initialize (valid exception to this rule: input variable) 22Stroustrup/Programming

A technical detail In memory, everything is just bits; type is what gives meaning to the bits In memory, everything is just bits; type is what gives meaning to the bits (bits/binary) is the int 97 is the char 'a' (bits/binary) is the int 65 is the char 'A' (bits/binary) is the int 48 is the char '0' char c = 'a'; cout << c;// print the value of character c, which is a int i = c; cout << i;// print the integer value of the character c, which is 97 This is just as in the real world: This is just as in the real world: What does 42 mean? What does 42 mean? You dont know until you know the unit used You dont know until you know the unit used Meters? Feet? Degrees Celsius? $s? a street number? Height in inches? … Meters? Feet? Degrees Celsius? $s? a street number? Height in inches? … 23Stroustrup/Programming

About Efficiency For now, dont worry about efficiency For now, dont worry about efficiency Concentrate on correctness and simplicity of code Concentrate on correctness and simplicity of code C++ is derived from C, which is a systems programming language 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 types map directly to computer main memory a char is stored in a byte a char is stored in a byte An int is stored in a word An int is stored in a word A double fits in a floating-point register A double fits in a floating-point register C++s built-in operations map directly to machine instructions C++s built-in operations map directly to machine instructions An integer + is implemented by an integer add operation An integer + is implemented by an integer add operation An integer = is implemented by a simple copy operation An integer = is implemented by a simple copy operation C++ provides direct access to most of the facilities provided by modern hardware C++ provides direct access to most of the facilities provided by modern hardware C++ help users build safer, more elegant, and efficient new types and operations using built-in types and operations. C++ help users build safer, more elegant, and efficient new types and operations using built-in types and operations. E.g., string E.g., string Eventually, well show some of how thats done Eventually, well show some of how thats done 24Stroustrup/Programming

A bit of philosophy One of the ways that programming resembles other kinds of engineering is that it involves tradeoffs. One of the ways that programming resembles other kinds of engineering is that it involves tradeoffs. You must have ideals, but they often conflict, so you must decide what really matters for a given program. You must have ideals, but they often conflict, so you must decide what really matters for a given program. Type safety Type safety Run-time performance Run-time performance Ability to run on a given platform Ability to run on a given platform Ability to run on multiple platforms with same results Ability to run on multiple platforms with same results Compatibility with other code and systems Compatibility with other code and systems Ease of construction Ease of construction Ease of maintenance Ease of maintenance Don't skimp on correctness or testing Don't skimp on correctness or testing By default, aim for type safety and portability By default, aim for type safety and portability 25Stroustrup/Programming

Another simple computation // inch to cm and cm to inch conversion: 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 cout << val << "in == " << val*cm_per_inch << "cm\n"; else if (unit == 'c')// 'c' for cm cout << val << "cm == " << val/cm_per_inch << "in\n"; else return 0;// terminate on a bad unit, e.g. 'q' }} 26Stroustrup/Programming

The next lecture Will talk about expressions, statements, debugging, simple error handling, and simple rules for program construction Will talk about expressions, statements, debugging, simple error handling, and simple rules for program construction 27Stroustrup/Programming