Download presentation
Presentation is loading. Please wait.
1
GETTING STARTED WITH C++ ID1218 Lecture 072009-11-18 Christian Schulte cschulte@kth.se Software and Computer Systems School of Information and Communication Technology KTH – Royal Institute of Technology Stockholm, Sweden
2
L07, 2009-11-18ID1218, Christian Schulte 2 Overview C++ Basics Basic types and control structures Functions and Arrays Pointers Some pragmatics…
3
L07, 2009-11-18ID1218, Christian Schulte 3 Goals Familiarize with programming in C/C++ Understand underlying programming model Understand language constructs program structure data structures and common algorithms memory management development pragmatics difference between C and C++ For later courses using C/C++
4
L07, 2009-11-18ID1218, Christian Schulte 4 Approach Not from scratch, build Java as programming language Efficient approach focus on essential not comprehensive apply practically
5
L07, 2009-11-18ID1218, Christian Schulte 5 Textbook C++ for Java Programmers, Mark Allen Weiss, Prentice Hall, 2004 good selection of issues and topic non-naïve: no repetition what you know concise (very important) valuable resource after course!!!
6
L07, 2009-11-18ID1218, Christian Schulte 6 Other Valuable Books: C++ Thick, verbose, but useful J. Lajoie and S. Lippmann, C++ Primer 3 rd edition, Addison-Wesley, 1998. Reference from the designer B. Stroustrup, The C++ Programming Language 3 rd edition, Addison-Wesley, 1997. Tips for advanced issues R. B. Murray, C++ Strategies and Tactics Addison-Wesley, 1993. C++ Standard library N. M. Josuttis, The C++ Standard Library Addison-Wesley, 1999.
7
L07, 2009-11-18ID1218, Christian Schulte 7 Other Valuable Books: C The classic B. W. Kernighan and D. M. Ritchie, The C Programming Language 2 nd edition, Prentice Hall, 1997 Great reference, portability, also useful for C++ S. P. Harbinson, G. L. Steele, C – A Reference Manual 5 th edition, Prentice Hall, 2002
8
L07, 2009-11-18ID1218, Christian Schulte 8 What? C++ as main vehicle basic issues pointers and references classes, objects, inheritance overview: operator overloading, templates, exceptions, input/output, standard library Contrast with main differences in C basic issues (arrays) memory management, input/output mixing C and C++
9
L07, 2009-11-18ID1218, Christian Schulte 9 Why? Study radically different model of computation not type safe: how to get along explicit memory management: no garbage collection, how to manage memory successfully close to abstraction level of machines Ideally, do it in Erlang… …but can't be done take the trouble and use C++/C can be used afterwards anyway
10
L07, 2009-11-18ID1218, Christian Schulte 10 How? Differential approach in contrast to Java: Java is close in many aspects Practical approach try most important aspects in labs/tutorials
11
L07, 2009-11-18ID1218, Christian Schulte 11 What Do I Expect? You will not become C++ wizards You will understand the basic issues characteristics of computation model characteristics of development pragmatics You will know where to look for further information language pragmatics
12
L07, 2009-11-18ID1218, Christian Schulte 12 Pragmatics How to organize programming projects automatize recompilationmake How to install software use configure How to develop how to find errors: debugging how to improve performance: profiling
13
L07, 2009-11-18ID1218, Christian Schulte 13 Labs Labs warm-up:introduction to pragmatics sound processing:to be handed in Sudoku solver:to be handed in Hand in: show to TA
14
L07, 2009-11-18ID1218, Christian Schulte 14 Reading Suggestions All of you thorough reading of chapters 0 to 3 take a peek at chapter 11 do it, the book is a great read! go through the exercises!
15
Getting Started in C++ L07, 2009-11-18 15 ID1218, Christian Schulte
16
L07, 2009-11-18ID1218, Christian Schulte 16 Our First C++ Program #include using namespace std; int main() { cout << "Hello world." << endl; return 0; }
17
L07, 2009-11-18ID1218, Christian Schulte 17 Hello World Explained Execution starts with main integer return value is error code (0 is okay) is normal function (a global function) functions in classes (methods): member functions can take additional arguments (command-line): later All C++ programs are preprocessed #include resolved by preprocessor refers to C++ system IO #include "my.h" includes local file my.h Other uses: multiply used files (declarations, headers)
18
L07, 2009-11-18ID1218, Christian Schulte 18 Hello World Explained… Standard functionality in namespace std becomes available by using namespace std; here: cout (standard output), endl (end of line) Input similarly: int x; cout << "Your age: "; cin >> x; cin refers to standard input also common: using C-style input/output
19
L07, 2009-11-18ID1218, Christian Schulte 19 In Java… public class Hello { public static void main(String[]) { System.out.println("Hello world"); }
20
L07, 2009-11-18ID1218, Christian Schulte 20 Compiling and Running Edit file emacs hello.cpp other extensions:.cc,.cxx,.C Invoke compiler to create executable g++ hello.cpp –o hello.exe we use the GNU C++ compiler (g++) Run executable./hello.exe
21
Basic Types and Control Structures L07, 2009-11-18 21 ID1218, Christian Schulte
22
L07, 2009-11-18ID1218, Christian Schulte 22 Primitive Types Integer types Floating point types Character types Boolean type Non-primitive types arrays, objects, pointers, references, …
23
L07, 2009-11-18ID1218, Christian Schulte 23 Integer Types Basic integer type int few guarantees on range in C++ today, often 32 bits, anytime soon 64 bits, … depends on machine (think of embedded…) Can be augmented with short or long int never shorter than short int (at least 16) int never longer than long int (at least 32) Can be modified with signed (default) or unsigned short signed int -32768 … 32767 short unsigned int 0 … 65535 just for example!
24
L07, 2009-11-18ID1218, Christian Schulte 24 Floating Point Types Single precision float often: 32 bits Double precision double often: 64 bits Again, few guarantees
25
L07, 2009-11-18ID1218, Christian Schulte 25 Character Type Character type char no guarantee on size, often 8 bits (ASCII, not Unicode!) unspecified whether signed or unsigned Character constants in single quotes 'a', '1' escape sequences: '\n' for newline, etc Also available: wchar_t for wide characters
26
L07, 2009-11-18ID1218, Christian Schulte 26 Boolean Type Boolean type bool constants true and false Rather late addition! watch out for int with zero as false and any other value true!
27
L07, 2009-11-18ID1218, Christian Schulte 27 Constants Variables taking an immutable value cannot be changed abbreviation for commonly used values Use const modifier const double pi = 3.1415; assignment to pi not possible
28
L07, 2009-11-18ID1218, Christian Schulte 28 Operators, Expressions, Statements Almost the same in C++ as in Java in general: C++ carries some historic weight, Java has cleaned up, so watch out for some gotchas Almost the same operators and expressions, conditionals, loops, … assignment: no guarantee of initialization Additionally casts: change/convert/ignore type type definitions
29
L07, 2009-11-18ID1218, Christian Schulte 29 Operators and Expressions No left to right order readInt() – readInt() with input 2 and 3 can be either 1 or -1 Integer division not guaranteed to round towards zero (book uses down) 8/-5 can be either -1 or -2 Comma operator: a,b evaluates to b weird things possible!
30
L07, 2009-11-18ID1218, Christian Schulte 30 Operators and Expressions No guarantee on shift a << b can be either arithmetic or logic arithmetic -1 << 1 remains negative logic -1 << 1 is positive
31
L07, 2009-11-18ID1218, Christian Schulte 31 Conditionals Condition can be either of type int or bool if (i) { … } else { … } If i is different from zero, take then part If i is zero, take else part not recommended, write if (i != 0) … Common mistake if (x = 0) … actually meant: if (x == 0) … assigns 0 to x, takes the else part write variable to the right, if possible: if (0 == x)
32
L07, 2009-11-18ID1218, Christian Schulte 32 Loops As in Java, along with break and continue
33
L07, 2009-11-18ID1218, Christian Schulte 33 Unitialized Variables Variables not by guarantee initialized unless global or static (later) Always give initial value important for objects (later)
34
L07, 2009-11-18ID1218, Christian Schulte 34 Typecasts for Primitive Types Automatic conversion double x = 6.0; int y; y=x; Typecasting can be essential int x=6; int y=10; double z = x/y; results in 0.0 rather than 0.6
35
L07, 2009-11-18ID1218, Christian Schulte 35 Static Casts Cast at least one into double static_cast (x)/y; Other casts dynamic_cast casting objects, later const_cast later reinterpret_cast just do it as size fits… C-style cast ((double) x) dangerous, combines everything, don't use!
36
L07, 2009-11-18ID1218, Christian Schulte 36 Type Definitions Give names to types Example: define implementation dependent integer type uint32 machine A: typedef unsigned long int uint32; machine B: typedef unsigned int uint32; rest of program can use uint32, does not require modification when being ported to machine C
37
Functions L07, 2009-11-18 37 ID1218, Christian Schulte
38
L07, 2009-11-18ID1218, Christian Schulte 38 Function Definition Function definition contains return type function name parameter list body Function can be called given function name and appropriate parameters Function can only be defined once
39
L07, 2009-11-18ID1218, Christian Schulte 39 Function Example int maxx(int x, int y) { return (x > y) ? x : y; }
40
L07, 2009-11-18ID1218, Christian Schulte 40 Function Invocation Print maximum of two numbers cout << maxx(43,27) << endl; Uses call-by-value Parameters need not be of type int automatic cast long int possibly with warning
41
L07, 2009-11-18ID1218, Christian Schulte 41 Function Overloading The same function name can be used multiply with different types in parameter list double maxx(double x, double y) { return (x>y) ? x : y; } Complicated set of rules describe which definition is chosen Overloading with different return type only not allowed
42
L07, 2009-11-18ID1218, Christian Schulte 42 Function Declarations Every function needs to be declared prior to invocation declared, but not defined! can be declared multiply A function declaration is done by giving a function prototype int maxx(int, int); or int maxx(int a, int b);
43
L07, 2009-11-18ID1218, Christian Schulte 43 Default Parameters Default values can be given for formal parameters if function has declaration, in declaration if function has only definition, in definition only allowed as last formal parameters Assume that maxx is often used with 0 as second argument int maxx(int, int = 0); Then the following invocation is legal int z = maxx(-45); In this case, definition remains unchanged
44
L07, 2009-11-18ID1218, Christian Schulte 44 Inline Functions Overhead of function call be significant: maxx is good example Give function definition an inline directive inline int maxx(int x, int y) { … } Invocation of function is replaced by body Definition must be textually before first invocation Compilers will also inline other, small functions
45
L07, 2009-11-18ID1218, Christian Schulte 45 Separate Compilation Structure larger programs into separate files each file contains some functions: better structure each file can be compiled independently: save compilation time during development Header file contains declarations and definitions of inline functions file name extensions:.h,.hh Implementation file contains definition of functions (implementation)
46
L07, 2009-11-18ID1218, Christian Schulte 46 Header File maxx.h /* * Declaration of maximum function */ int maxx(int, int);
47
L07, 2009-11-18ID1218, Christian Schulte 47 Implementation File maxx.cpp #include "maxx.h" int maxx(int x, int y) { return (x > y) ? x : y; }
48
L07, 2009-11-18ID1218, Christian Schulte 48 Main File main.cpp #include #include "maxx.h" int main() { std::cout << maxx(47,23) << std::endl; return 0; }
49
L07, 2009-11-18ID1218, Christian Schulte 49 Putting Everything Together Compile each implementation file independently g++ -c main.cpp g++ -c maxx.cpp creates the files main.o and maxx.o contain object code but require linking Put everything together (linking) g++ main.o maxx.o –o main.exe
50
L07, 2009-11-18ID1218, Christian Schulte 50 Include Each Header at Most Once Remember: inline functions must be defined not only declared before usage Remember: at most one definition! what if header is included from other header files possibly having multiple definitions of same function also: why read same header more than once? Use preprocessor (also macro processor) to guarantee at- most-once inclusion define a preprocessor variable when included test whether preprocessor variable not already defined choose reasonably unique name
51
L07, 2009-11-18ID1218, Christian Schulte 51 Fixed Header File maxx.h /* * Declaration of maximum function */ #ifndef __MAXX_H__ #define __MAXX_H__ int maxx(int, int); #endif
52
L07, 2009-11-18ID1218, Christian Schulte 52 Organizing Compilation How to organize compilation recompilation needed if included header file changes compilation can be time-consuming: > 1000 files? only recompile what is needed Use make: express dependencies among files files only recompiled, if dependencies change rules for how to perform compilation.cpp .o.o .exe later (first lab session) more
53
Arrays L07, 2009-11-18 53 ID1218, Christian Schulte
54
L07, 2009-11-18ID1218, Christian Schulte 54 C-style Arrays C-style arrays int a[42]; creates an array of 42 integers access cout << a[1]; assignment a[1] = a[2]+a[3]; ranges from a[0] to a[41] Dimension of array must be constant can be evaluated at compile time to constant (eg 2*4 ) illegal int a[n] where n is variable!
55
L07, 2009-11-18ID1218, Christian Schulte 55 Using Arrays as Parameters int find_max(int a[], int n) { int m = a[0]; for (int i = 1; i<n; i++) if (a[i] > m) m=a[i]; return m; } Array of arbitrary size int a[] requires to pass size as extra parameter int n
56
L07, 2009-11-18ID1218, Christian Schulte 56 Using Arrays as Parameters int find_max(int a[42]) { int m = a[0]; for (int i = 1; i<42; i++) if (a[i] > m) m=a[i]; return m; } Supports only arrays statically known to have size 42!
57
L07, 2009-11-18ID1218, Christian Schulte 57 Allocating Arrays What if size is not known statically memory for array must be allocated from heap after use, memory must be explicitly freed C++ style memory management use new [] and delete [] special versions for arrays normal versions to be used later for objects
58
L07, 2009-11-18ID1218, Christian Schulte 58 Allocating Arrays Allocate an array of integers with size n new int[n]; Free memory array (no matter its size or type) delete [] a; The following does not work int a[] = new int[n]; a must have know size, or used as parameter use pointers rather than arrays (a little later)
59
L07, 2009-11-18ID1218, Christian Schulte 59 Primitive Arrays of Constants Initialize arrays in declaration declare array to be not assignable const int DIM[] = {31,28,31,30,31,30, 31,31,30,31,30,31}; declares array of size 12
60
L07, 2009-11-18ID1218, Christian Schulte 60 C-Style Strings Use arrays of chars! Often const char s[] = "A C-string."; contains all letters given plus 0 at the end (end-of-string marker) has size 12 (additional 0)
61
L07, 2009-11-18ID1218, Christian Schulte 61 Vectors and C++ Strings Vectors are C++ arrays #include automatic resize automatic memory management copied when passed as parameters Strings #include same advantages as above support for comparison, copying on assignment, … Please read book about both vectors and strings
62
Parameter Passing L07, 2009-11-18 62 ID1218, Christian Schulte
63
L07, 2009-11-18ID1218, Christian Schulte 63 Call By-value Default mechanism already seen works by copying: straightforward for primitive types but copying also for objects: to be discussed later! What if one return value is not enough? use call by-reference
64
L07, 2009-11-18ID1218, Christian Schulte 64 Call By-reference Function to exchange to values, first attempt (wrong): void exc(int a, int b) { int t=a; a=b; b=t; } just works on copies passed to exc need to pass references instead
65
L07, 2009-11-18ID1218, Christian Schulte 65 Call By-reference Function to exchange to values (correct): void exc(int &a, int &b) { int t=a; a=b; b=t; } a and b are passed by reference effect is on actual parameters int x = 4; int y = 5; exc(x,y); constants are not allowed as actual parameters exc(x,5);
66
Pointers: Outlook L07, 2009-11-18 66 ID1218, Christian Schulte
67
L07, 2009-11-18ID1218, Christian Schulte 67 Pointers Are a consequence that memory management is not abstracted away Erlang and Java: all variables hold references to values, operations are performed implicitly on value C and C++ distinguish objects (also primitive values) pointers: values which point to memory address of objects
68
L07, 2009-11-18ID1218, Christian Schulte 68 Pointers Declaring a pointer to an integer int* p; Let p point to address of x int x = 5; p = &x; & is called unary address-of operator Read value at pointer: prints 5 cout << *p; * is called unary dereference operator Store value at memory referenced at p: prints 7 *p = 7; cout << x;
69
L07, 2009-11-18ID1218, Christian Schulte 69 Pointers Illustrated… After declaration int x = 10; int y = 7; int* p; p points somewhere (unitialized) (&x) 100 x = 10 (&y) 104 y = 7…… (&p) 200 p = ????…
70
L07, 2009-11-18ID1218, Christian Schulte 70 Segmentation Fault or Bus Error… Assign object pointed to by p a value *p = 124; but: not necessarily, p can also point to some other location (overrides other variables contents…) (&x) 100 x = 10 (&y) 104 y = 7…… (&p) 200 p = ????…
71
L07, 2009-11-18ID1218, Christian Schulte 71 Redirecting… Let p point to location of x p = &x; (&x) 100 x = 10 (&y) 104 y = 7…… (&p) 200 p = &x = 100…
72
L07, 2009-11-18ID1218, Christian Schulte 72 Assigning… Assign object pointed to by p a value *p = 5; (&x) 100 x = 5 (&y) 104 y = 7…… (&p) 200 p = &x = 100…
73
L07, 2009-11-18ID1218, Christian Schulte 73 Redirecting… Let p point to location of y p = &y; (&x) 100 x = 5 (&y) 104 y = 7…… (&p) 200 p = &y = 104…
74
L07, 2009-11-18ID1218, Christian Schulte 74 Assigning… Assign object pointed to by p a value *p = 99; (&x) 100 x = 5 (&y) 104 y = 99…… (&p) 200 p = &y = 104…
75
L07, 2009-11-18ID1218, Christian Schulte 75 Common Idioms Testing that pointers refer to same location p1 == p2 Testing that objects pointed to have same value *p1 == *p2 Use NULL for ptr not pointing anywhere const int NULL = 0; use in initialization, tests, etc
76
L07, 2009-11-18ID1218, Christian Schulte 76 Heap Memory Management Get memory from heap int* p = new int; allocate memory block big enough for one int After use, release delete p;
77
L07, 2009-11-18ID1218, Christian Schulte 77 Getting It Wrong Forget to delete program crashes when running out of memory Delete to early lucky case: program crashes due to OS knowing that memory has been freed unlucky case: already reused, arbitrary things can happen! Delete twice runtime error
78
L07, 2009-11-18ID1218, Christian Schulte 78 What Is Next? Storage classes automatic and static variables Arrays are pointers int* a = new int[n];
79
Summary L07, 2009-11-18 79 ID1218, Christian Schulte
80
L07, 2009-11-18ID1218, Christian Schulte 80 Summary Radically new computation model not type safe explicit memory management Few guarantees primitive types and their operations Memory management is very difficult!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.