1 / 47

Objects, types, and values

Objects, types, and values. Adapted from Bjarne Stroustrup www.stroustrup.com/Programming X. Zhang Fordham Univ. CISC1600, Spring 2012. /* This is a program that simply prints out Hello world to the terminal, and move cursor to next line By X. Zhang, last updated 1/30/2012

Télécharger la présentation

Objects, types, and values

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Objects, types, and values Adapted from BjarneStroustrup www.stroustrup.com/Programming X. Zhang Fordham Univ. CISC1600, Spring 2012

  2. /* This is a program that simply prints out Hello world • to the terminal, and move cursor to next line • By X. Zhang, • last updated 1/30/2012 • */ • #include <iostream> //This is preprocessor directive • using namespace std; // In order to use cin, cout etc declared in std • int main() • { • cout <<"Hello world\n"; // send the string to the terminal window • // this is a blank line, added here for readability • return 0; //program exits, return 0 to indicate success • } Curly braces enclose the body of function Statement (end with ;) CS1, Spring 2012, Zhang

  3. Cout statement cout <<"Hello world\n"; • cout: pronounced as see-out, stands for character output • Defined in iostream, a header file (a source code) that is part of C++ standard library • Represents the terminal window that the program is running from • << insertion operator: to insert (display) something in terminal window • Can display multiple values in single statement, e.g., • cout <<“Hello world, “ << “this is my first program!\n”; • cout <<“Hello world, “ << “this is my first program!\n”; One statement can be split into multiplie lines. CS1, Spring 2012, Zhang

  4. Overview • Introduction • Strings and string I/O • Integers and integer I/O • Type of a variable decides what operations can be performed on it • Types and objects • C++ built-in types, user-defined types • literals • Simple arithmetic • More next week • Type safety CS1, Spring 2012, Zhang

  5. Computation • Input: from keyboard, files, other input devices, other programs, other parts of a program • Computation – what our program will do with the input to produce the output. • Output: to screen, files, other output devices, other programs, other parts of a program Code, often messy, often a lot of code (input) data (output) data data Stroustrup/Programming

  6. Computation (cont’d) • What are inputs, computation, and outputs of following program? • Hello world program • Editor • Windows Media Player • Calculator • Video game • We now extend hello world to take some input … CS1, Spring 2012, Zhang

  7. Program structure 1 Read inputs 2 Computation 3 Write output 1 Read inputs 2 Computation 3 Write output 4 Go back to 1 Single batch of input Multiple batch of input CS1, Spring 2012, Zhang

  8. 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 CS1, Spring 2012, Zhang

  9. Input and type • We read data/or input into a variable • Here, first_name • A variable has a type • Here, string • 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 • White space: space, tab, newline, … CS1, Spring 2012, Zhang

  10. 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 CS1, Spring 2012, Zhang

  11. 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'; } CS1, Spring 2012, Zhang

  12. Integers and Strings • 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 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") CS1, Spring 2012, Zhang

  13. Overview • Introduction • Strings and string I/O • Integers and integer I/O • Type of a variable decides what operations can be performed on it • Types and objects • C++ built-in types, user-defined types • Variable declaration, literals • Simple arithmetic • More next week • Type safety CS1, Spring 2012, Zhang

  14. Types • C++ provides a set of types • E.g. bool, char, int, double • Called “built-in types” • C++ programmers can define new types • Called “user-defined types” • We'll get to that eventually • C++ standard library provides a set of types • E.g. string, vector, complex • Technically, these are user-defined types • they are built using only facilities available to every user CS1, Spring 2012, Zhang

  15. Builtin Types • Boolean type represents value of true or false • bool • ex: boolinvalidInput; // used to mark invalid input • Character type represents a single character, such as q, a, B, \n, (, … • char • Ex: char choice = ‘q’; • Integer types • int • short and long • Floating-point types • Double • and float CS1, Spring 2012, Zhang

  16. Builtin Types • Boolean type represents value of true or false • bool • ex: boolinvalidInput; // used to mark invalid input • Character type represents a single character, such as q, a, B, \n, (, … • char • Ex: char choice = ‘q’; • Integer types represents a whole number • int, short and long • Floating-point types represents number with decimal points, such as 3.14 • double, and float CS1, Spring 2012, Zhang

  17. Number types • Integer numbers (int) are whole numbers without a fractional part • Includes zero and negative numbers • Used for storing values that are conceptually whole numbers (e.g. pennies) • Process faster and require less storage space • Floating-point numbers (double) have decimal points CS1, Spring 2012, Zhang

  18. Objects • An object is some memory that can hold a value of a given type • A variable is a named object; a constant is an object without a name, i.e., unaddressable • Each variable has name, type, value A declaration names an object int a = 7; char c = 'x'; string s = "qwerty"; a: 7 c: 'x' 6 s: "qwerty" Size of memory varies for objects of different types ! CS1, Spring 2012, Zhang

  19. Names in C++ • Starts with a letter, contains letters, digits, and underscores (only) • x, number_of_elements, Fourier_transform, z2 • Not names: • 12x • time$to$market • main line • Do not start names with underscores: _foo • those are reserved for implementation and systems entities • Users can't define names that are taken as keywords (or reserved words) • E.g.: int, if,while, double, main, … CS1, Spring 2012, Zhang

  20. Choose Meaningful Names • Abbreviations and acronyms can confuse people • mtbf, TLA, myw, nbv • Short names can be meaningful • when used conventionally: • x is a local variable • i is a loop index • Don't use overly long names • Ok: • partial_sumelement_countstaple_partition • Too long: • the_number_of_elementsremaining_free_slots_in_the_symbol_table CS1, Spring 2012, Zhang

  21. Variable DECLARATION statement Syntax: type_namevariable_name; type_namevariable_name = initial_value; type_name variable_name1, variable_name2; Example: • double total; • int pennies = 8; // 8 is a literal constant • int pennies, nickels, dimes, quarters; Purpose: • Define a new variable of a particular type, and optionally supply an initial value. All statements end with ; CS1, Spring 2012, Zhang

  22. Types and literals int pennies = 8; cout << “Hello world\n”; • Literal constants: values that occurs in the program • Literal, as we can only speak of it in terms of its value • Constant: its value cannot be changed • How to write literals? • Depending on the type of the literal • 8 is of type int, “Hello world\n” is of type string • More examples: • boolvalidInput = true; • bool continue = false; // reserved words • Character literals: 'a', 'x', '4', '\n', '$‘ • Integer literals: 0, 1, 123, -6, 0x34, 0xa3, 024 • Floating point literals: 1.2, 13.345, .3, -0.54, 1.2e3, . 3F, .3F • String literals: "asdf", "Howdy, all y'all!“ CS1, Spring 2012, Zhang

  23. Overview • Introduction • Strings and string I/O • Integers and integer I/O • Type of a variable decides what operations can be performed on it • Types and objects • C++ built-in types, user-defined types • literals • Operations and Operators • Some examples • Type safety CS1, Spring 2012, Zhang

  24. Operation on data • Once we have variables and constants, we can begin to operate with them. • C++ defines operators. • Operators in C++ are mostly made of signs that are not part of the alphabet but are available in all keyboards. • Shorter C++ code and more international CS1, Spring 2012, Zhang

  25. Operators • Assignment (=) • The assignment operator assigns a value to a variable. • Arithmetic operators ( +, -, *, /, % ) • five arithmetical operations supported by the C++ language are • Addition: + • subtraction: - • Multiplication: * • Division: / • Modulo: %, gives remainder of a division of two values.  a = 11 % 3; // a will contain the value of 2 CS1, Spring 2012, Zhang

  26. Assignment and increment a: // changing the value of a variable int a = 7; // a variable of typeintcalled a // initialized to the integer value 7 a = 9; // assignment: now change a's value to 9 a = a+a; // assignment: now doublea'svalue a += 2; // increment a's value by 2 // a shorthand notation for a = a+2; ++a; // increment a's value (by 1) //shorthand notation for a = a+1; 7 9 18 20 21 CS1, Spring 2012, Zhang

  27. Simple arithmetic // do a bit of very simple arithmetic: #include <math.h> 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 } If the user enters 25 upon the prompt, what’s the output? CS1, Spring 2012, Zhang

  28. Overview • Introduction • Strings and string I/O • Integers and integer I/O • Type of a variable decides what operations can be performed on it • Types and objects • C++ built-in types, user-defined types • literals • Simple arithmetic • More next week • Type safety CS1, Spring 2012, Zhang

  29. Types and Objects: a closer look • A type defines a set of possible values and a set of operations • A value is a sequence of bits in memory, interpreted according to its type • An object is a piece of memory that holds a value of a given type int a = 7; char c = 'x'; string s = "qwerty"; a: 7 c: x String object keeps the # of chars in the string, and the chars .. We will learn how to access each char, s[0], s[1], … 6 qwerty s: CS1, Spring 2012, Zhang

  30. More example • What’s the difference? double x=12; string s2=“12”; • x stores the value of number 12 s2 stores the two characters, ‘1’,’2’ • applicable operations are different x: arithmetic operations, numerical comparison, s2: string concatenation, string comparison x: 12 s2: 2 12 CS1, Spring 2012, Zhang

  31. value:a sequence of bits in memory • interpreted according to a type • E,g, int x=8; • is represented in memory as a seq. of binary digits (i.e., bits): • An integer value is stored using the value’s binary representation (demo this) • In everyday life, we use decimal representation x: 8 CS1, Spring 2012, Zhang

  32. value:a sequence of bits in memory (cont’d) • interpreted according to a type • E,g, char x=‘8’; • is represented in memory as a seq. of binary digits (i.e., bits) • A char value is stored using char’s ASCII code x: ‘8’ CS1, Spring 2012, Zhang

  33. ASCII Code CS1, Spring 2012, Zhang

  34. A bit sequence (string) Interpretation • Given a bit string in memory • If it’s interpreted as integer, then it represents value 8 • 1*23=8 • If interpreted as char, there are two chars, a NULL char, and a BACKSPACE char CS1, Spring 2012, Zhang

  35. A technical detail • In memory, everything is just bits; type is what gives meaning to the bits char c = 'a'; cout << c; // print the value of character variable c, which is a inti = c; cout << i; // print the integer value of the character c, which is 97 inti = c; • Assign a char value to a int type variable ?! • A safe type conversion ! Why? • Left-hand-side (LHS) • is an int type variable • Right-hand-side (RHS) is • a value of char type CS1, Spring 2012, Zhang

  36. Sizeof operator Yields size of its operand with respect to size of type char. cout <<"sizeof bool is " << sizeof (bool) << "\n" <<"sizeof char is " << sizeof (char) << "\n" <<"sizeof int is " << sizeof (int) << "\n" <<"sizeof short is " << sizeof (short) << "\n" <<"sizeof long is " << sizeof (long) << "\n" <<"sizeof double is " << sizeof (double) << "\n" <<"sizeof float is " << sizeof (float) << "\n"; sizeof bool is 1 sizeof char is 1 sizeof int is 4 sizeof short is 2 sizeof long is 8 sizeof double is 8 sizeof float is 4 CS1, Spring 2012, Zhang

  37. Char-to-int conversion char c = 'a'; cout << c; // print the value of character variable c, which is a inti = c; cout << i; // print the integer value of the character c, which is 97 • No information is lost in the conversion char c2=i; //c2 has same value as c • Can convert int back to char type, and get the original value • Safe conversion: • bool to char, int, double • char to int, double • int to double c: 01100001 0000000000000000000000001100001 i: CS1, Spring 2012, Zhang

  38. Type safety • Type safety is extent to which a programming language discourages or prevents type errors. • Ideally, every object will be used only according to its type • A variable will be used only after it has been initialized • 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 • E.g., double x; //x is not initialized, // memory contains random bit string • double y=x; //use uninitialized x CS1, Spring 2012, Zhang

  39. #include <iostream> using namespace std; int main() { int pennies = 8; //what if change 8 to "eight"? int dimes = 4; int quarters = 3; double total = pennies * 0.01 + dimes * 0.10 + quarters * 0.25; // Total value of the coins cout << "Total value = " << total << "\n"; return 0; } Implicit type conversion int to double CS1, Spring 2012, Zhang

  40. Type safety ENFORCEMENT • A language supports static type safety if • A program that violates type safety will not compile • Compiler reports every violation • “when you program, the compiler is your best friend” • A language supports dynamic type safety, if • a program that violates type safety it will be detected at run time • Some code (typically “ run-time system") detects every violation not found by compiler CS1, Spring 2012, Zhang

  41. C++ Type safety • C++ is not (completely) statically type safe • No widely-used language is (completely) statically type safe • C++ is not (completely) dynamically type safe • Many languages are dynamically type safe • Being completely statically or dynamically type safe may interfere with the ability to express ideas and often makes generated code bigger and/or slower • A trade-off ! • Most of what you’ll be taught here is type safe • We’ll specifically mention anything that is not CS1, Spring 2012, Zhang

  42. 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"; } (demo2.cpp) Try it to see what value b gets on your machine, why? 20000 a ??? c: ?? b CS1, Spring 2012, Zhang

  43. “narrowing” conversion int main() { double d =0; while (cin>>d) { // repeat the statements below // as long as we type in numbers int i = d; // try to squeeze a double into an int char c = i; // try to squeeze an int into a char int i2 = c; // get the integer value of the character cout << "d==" << d // the original double << " i=="<< i // converted to int << " i2==" << i2 // int value of char << " char(" << c << ")\n"; // the char } Demo: TestCode/narrow CS1, Spring 2012, Zhang

  44. 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 //can’t 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 CS1, Spring 2012, Zhang

  45. A bit of philosophy • 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. • 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 CS1, Spring 2012, Zhang

  46. Summary • Introduction • Strings and string I/O • Integers and integer I/O • Type of a variable decides what operations can be performed on it • Types and objects • C++ built-in types, user-defined types • literals • Simple arithmetic • More next week • Type safety CS1, Spring 2012, Zhang

  47. The next lecture • Copy sample code and try them out yourself • Read chapter 4, email me questions • Will talk about expressions, statements, debugging, simple error handling, and simple rules for program construction CS1, Spring 2012, Zhang

More Related