3_types

3_types - Simple arithmetic // do a bit of very simple...

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: 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 } Stroustrup/Programming 1 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"; } } A while-statement repeatedly executes until its condition becomes false Stroustrup/Programming 2 Types and literals Built-in types Boolean type bool Character types char Integer types int 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, .3F String literals "asdf", "Howdy, all y'all!" Complex literals and short and long Floating-point types double and float Standard-library types string complex<Scalar> complex<double>(12.3,99) If (and only if) you need more details, see the book! Stroustrup/Programming complex<float>(1.3F) 3 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 E.g. string, vector, complex Technically, these are user-defined types The C++ standard library provides a set of types they are built using only facilities available to every user Stroustrup/Programming 4 Declaration and initialization int a = 7; int b = 9; char c = 'a'; double x = 1.2; string s1 = "Hello, world"; string s2 = "1.2"; s1: s2: x: 12 3 | | a: b: c: 1.2 "Hello, world" "1.2" 7 9 'a' Stroustrup/Programming 5 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 a: c: z: 'x' 1.0 2.0 7 int a = 7; char c = 'x'; complex<double> z(1.0,2.0); string s = "qwerty"; s: 6 "qwerty" Stroustrup/Programming 6 Type safety Language rule: type safety 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 Ideal: static type safety A program that violates type safety will not compile 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 detected at run time Some code (typically "the run-time system") detects every violation not found by the compiler (in an ideal system) Stroustrup/Programming 7 Type safety Type safety is a very big deal Try very hard not to violate it "when you program, the compiler is your best friend" But it won't feel like that when it rejects code you're sure is correct 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 express ideas 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 We'll specifically mention anything that is not Stroustrup/Programming 8 C++ is not (completely) dynamically type safe Most of what you'll be taught here is type safe Assignment and increment a: // changing the value of a variable int a = 7; // a variable of type int called a // initialized to the integer value 7 a = 9; // assignment: now change a's value to 9 a = a+a; a += 2; ++a; // assignment: now double a's value // increment a's value by 2 // increment a's value (by 1) 7 9 18 20 21 Stroustrup/Programming 9 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() { 20000 a int a = 20000; char c = a; ??? c: 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 Stroustrup/Programming 10 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; char c; double d; // x gets a "random" initial value // c gets a "random" initial value // 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) Stroustrup/Programming 11 } A technical detail In memory, everything is just bits; type is what gives meaning to the bits (bits/binary) 01100001 is the int 97 is the char 'a' (bits/binary) 01000001 is the int 65 is the char 'A' (bits/binary) 00110000 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": What does "42" mean? You don't know until you know the unit used Meters? Feet? Degrees Celsius? $s? a street number? Height in inches? ... Stroustrup/Programming 12 About Efficiency For now, don't worry about "efficiency" Concentrate on correctness and simplicity of code C++'s built-in types map directly to computer main memory C++ is derived from C, which is a systems programming language a char is stored in a byte An int is stored in a word A double fits in a floating-point register An integer + is implemented by an integer add operation An integer = is implemented by a simple copy operation C++'s built-in operations map directly to machine instructions 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. E.g., string Eventually, we'll show some of how that's done Stroustrup/Programming 13 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 Stroustrup/Programming 14 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' } } Stroustrup/Programming 15 The next lecture Will talk about expressions, statements, debugging, simple error handling, and simple rules for program construction Stroustrup/Programming 16 ...
View Full Document

Ask a homework question - tutors are online