Getting Started With C++

80
GETTING STARTED WITH C++ ID1218 Lecture 07 2009-11-18 Christian Schulte [email protected] Software and Computer Systems School of Information and Communication Technology KTH – Royal Institute of Technology Stockholm, Sweden

description

Christian Schulte [email protected] Software and Computer Systems School of Information and Communication Technology KTH – Royal Institute of Technology Stockholm, Sweden. Getting Started With C++. ID1218 Lecture 07 2009-11-18. Overview. C++ Basics Basic types and control structures - PowerPoint PPT Presentation

Transcript of Getting Started With C++

Page 1: Getting Started With C++

GETTING STARTED WITH C++

ID1218 Lecture 07 2009-11-18

Christian [email protected]

Software and Computer SystemsSchool of Information and Communication

TechnologyKTH – Royal Institute of Technology

Stockholm, Sweden

Page 2: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

2

Overview C++ Basics

Basic types and control structures Functions and Arrays Pointers Some pragmatics…

Page 3: Getting Started With C++

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++

Page 4: Getting Started With C++

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

Page 5: Getting Started With C++

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!!!

Page 6: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

6

Other Valuable Books: C++ Thick, verbose, but useful

J. Lajoie and S. Lippmann, C++ Primer3rd edition, Addison-Wesley, 1998.

Reference from the designerB. Stroustrup, The C++ Programming Language3rd edition, Addison-Wesley, 1997.

Tips for advanced issuesR. B. Murray, C++ Strategies and TacticsAddison-Wesley, 1993.

C++ Standard libraryN. M. Josuttis, The C++ Standard LibraryAddison-Wesley, 1999.

Page 7: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

7

Other Valuable Books: C The classic

B. W. Kernighan and D. M. Ritchie, The C Programming Language2nd edition, Prentice Hall, 1997

Great reference, portability, also useful for C++

S. P. Harbinson, G. L. Steele, C – A Reference Manual5th edition, Prentice Hall, 2002

Page 8: Getting Started With C++

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++

Page 9: Getting Started With C++

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

Page 10: Getting Started With C++

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

Page 11: Getting Started With C++

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

Page 12: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

12

Pragmatics How to organize programming projects

automatize recompilation make

How to install software use configure

How to develop how to find errors: debugging how to improve performance: profiling

Page 13: Getting Started With C++

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

Page 14: Getting Started With C++

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!

Page 15: Getting Started With C++

Getting Started in C++

L07, 2009-11-18

15

ID1218, Christian Schulte

Page 16: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

16

Our First C++ Program#include <iostream>using namespace std;

int main() { cout << "Hello world." << endl; return 0;}

Page 17: Getting Started With C++

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 <iostream> refers to C++ system IO #include "my.h" includes local file my.h Other uses: multiply used files (declarations,

headers)

Page 18: Getting Started With C++

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

Page 19: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

19

In Java…

public class Hello {

public static void main(String[]) { System.out.println("Hello world"); }}

Page 20: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

20

Compiling and Running Edit file

emacs hello.cpp other extensions: .cc, .cxx, .C

Invoke compiler to create executableg++ hello.cpp –o hello.exe

we use the GNU C++ compiler (g++) Run executable

./hello.exe

Page 21: Getting Started With C++

Basic Types and Control Structures

L07, 2009-11-18

21

ID1218, Christian Schulte

Page 22: Getting Started With C++

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, …

Page 23: Getting Started With C++

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!

Page 24: Getting Started With C++

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

Page 25: Getting Started With C++

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

Page 26: Getting Started With C++

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!

Page 27: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

27

Constants Variables taking an immutable value

cannot be changed abbreviation for commonly used values

Use const modifierconst double pi = 3.1415;

assignment to pi not possible

Page 28: Getting Started With C++

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

Page 29: Getting Started With C++

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/-5can be either -1 or -2

Comma operator: a,b evaluates to b weird things possible!

Page 30: Getting Started With C++

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

Page 31: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

31

Conditionals Condition can be either of type int or

boolif (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 mistakeif (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)

Page 32: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

32

Loops As in Java, along with break and continue

Page 33: Getting Started With C++

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)

Page 34: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

34

Typecasts for Primitive Types Automatic conversion

double x = 6.0; int y; y=x;

Typecasting can be essentialint x=6; int y=10; double z = x/y;

results in 0.0 rather than 0.6

Page 35: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

35

Static Casts Cast at least one into double

static_cast<double>(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!

Page 36: Getting Started With C++

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

Page 37: Getting Started With C++

Functions

L07, 2009-11-18

37

ID1218, Christian Schulte

Page 38: Getting Started With C++

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

Page 39: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

39

Function Exampleint maxx(int x, int y) { return (x > y) ? x : y;}

Page 40: Getting Started With C++

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

Page 41: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

41

Function Overloading The same function name can be used

multiply with different types in parameter listdouble 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

Page 42: Getting Started With C++

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);

Page 43: Getting Started With C++

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

Page 44: Getting Started With C++

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

Page 45: Getting Started With C++

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)

Page 46: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

46

Header File maxx.h/* * Declaration of maximum function */

int maxx(int, int);

Page 47: Getting Started With C++

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;}

Page 48: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

48

Main File main.cpp#include <iostream>#include "maxx.h"

int main() { std::cout << maxx(47,23) << std::endl; return 0;}

Page 49: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

49

Putting Everything Together Compile each implementation file

independentlyg++ -c main.cppg++ -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

Page 50: Getting Started With C++

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

Page 51: Getting Started With C++

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

Page 52: Getting Started With C++

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

Page 53: Getting Started With C++

Arrays

L07, 2009-11-18

53

ID1218, Christian Schulte

Page 54: Getting Started With C++

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) illegalint a[n] where n is variable!

Page 55: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

55

Using Arrays as Parametersint 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

Page 56: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

56

Using Arrays as Parametersint 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!

Page 57: Getting Started With C++

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

Page 58: Getting Started With C++

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 workint a[] = new int[n];

a must have know size, or used as parameter use pointers rather than arrays (a little later)

Page 59: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

59

Primitive Arrays of Constants Initialize arrays in declaration

declare array to be not assignableconst int DIM[] = {31,28,31,30,31,30, 31,31,30,31,30,31};

declares array of size 12

Page 60: Getting Started With C++

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)

Page 61: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

61

Vectors and C++ Strings Vectors are C++ arrays

#include <vector> automatic resize automatic memory management copied when passed as parameters

Strings #include <string> same advantages as above support for comparison, copying on assignment, …

Please read book about both vectors and strings

Page 62: Getting Started With C++

Parameter Passing

L07, 2009-11-18

62

ID1218, Christian Schulte

Page 63: Getting Started With C++

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

Page 64: Getting Started With C++

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

Page 65: Getting Started With C++

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 parametersexc(x,5);

Page 66: Getting Started With C++

Pointers: Outlook

L07, 2009-11-18

66

ID1218, Christian Schulte

Page 67: Getting Started With C++

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

Page 68: Getting Started With C++

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;

Page 69: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

69

Pointers Illustrated…

After declarationint x = 10;int y = 7;int* p;

p points somewhere (unitialized)

(&x) 100 x = 10(&y) 104 y = 7

…(&p) 200 p = ????

Page 70: Getting Started With C++

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 = ????

Page 71: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

71

Redirecting…

Let p point to location of xp = &x;

(&x) 100 x = 10(&y) 104 y = 7

…(&p) 200 p = &x = 100

Page 72: Getting Started With C++

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

Page 73: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

73

Redirecting…

Let p point to location of yp = &y;

(&x) 100 x = 5(&y) 104 y = 7

…(&p) 200 p = &y = 104

Page 74: Getting Started With C++

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

Page 75: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

75

Common Idioms Testing that pointers refer to same

locationp1 == 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

Page 76: Getting Started With C++

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, releasedelete p;

Page 77: Getting Started With C++

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

Page 78: Getting Started With C++

L07, 2009-11-18ID1218, Christian Schulte

78

What Is Next? Storage classes

automatic and static variables

Arrays are pointersint* a = new int[n];

Page 79: Getting Started With C++

Summary

L07, 2009-11-18

79

ID1218, Christian Schulte

Page 80: Getting Started With C++

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!