15 - KTH

advertisement

GETTING STARTED WITH

C++

Christian Schulte

cschulte@kth.se

Software and Computer Systems

School of Information and Communication Technology

KTH – Royal Institute of Technology

Stockholm, Sweden

ID1218 Lecture 07 2009-11-18

Overview

2

C++ Basics

 Basic types and control structures

Functions and Arrays

Pointers

Some pragmatics…

ID1218, Christian Schulte L07, 2009-11-18

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

ID1218, Christian Schulte L07, 2009-11-18

Approach

4

Not from scratch, build

Java as programming language

Efficient approach

 focus on essential

 not comprehensive

 apply practically

ID1218, Christian Schulte L07, 2009-11-18

Textbook

5

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

ID1218, Christian Schulte L07, 2009-11-18

Other Valuable Books: C++

6

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.

ID1218, Christian Schulte L07, 2009-11-18

Other Valuable Books: C

7

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

ID1218, Christian Schulte L07, 2009-11-18

What?

8

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

ID1218, Christian Schulte L07, 2009-11-18

Why?

9

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

ID1218, Christian Schulte L07, 2009-11-18

How?

10

Differential approach

 in contrast to Java: Java is close in many aspects

Practical approach

 try most important aspects in labs/tutorials

ID1218, Christian Schulte L07, 2009-11-18

What Do I Expect?

11

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

ID1218, Christian Schulte L07, 2009-11-18

Pragmatics

12

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

ID1218, Christian Schulte L07, 2009-11-18

Labs

13

Labs

 warm-up:

 sound processing:

Sudoku solver:

 Hand in: show to TA introduction to pragmatics to be handed in to be handed in

ID1218, Christian Schulte L07, 2009-11-18

Reading Suggestions

14

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!

ID1218, Christian Schulte L07, 2009-11-18

15

Getting Started in C++

ID1218, Christian Schulte L07, 2009-11-18

Our First C++ Program

16

#include <iostream> using namespace std; int main() { cout << "Hello world." << endl; return 0;

}

ID1218, Christian Schulte L07, 2009-11-18

Hello World Explained

17

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)

ID1218, Christian Schulte L07, 2009-11-18

Hello World Explained…

18

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

ID1218, Christian Schulte L07, 2009-11-18

In Java…

19 public class Hello {

} public static void main(String[]) {

System.out.println("Hello world");

}

ID1218, Christian Schulte L07, 2009-11-18

Compiling and Running

20

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

ID1218, Christian Schulte L07, 2009-11-18

21

Basic Types and Control Structures

ID1218, Christian Schulte L07, 2009-11-18

Primitive Types

22

Integer types

Floating point types

Character types

Boolean type

Non-primitive types

 arrays, objects, pointers, references, …

ID1218, Christian Schulte L07, 2009-11-18

Integer Types

23

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 int never longer than short int (at least 16) long int (at least 32)

Can be modified with signed (default) or unsigned

 short signed int

 short unsigned int just for example!

-32768 … 32767

0 … 65535

ID1218, Christian Schulte L07, 2009-11-18

Floating Point Types

24

Single precision

 often: 32 bits

Double precision

 often: 64 bits

Again, few guarantees float double

ID1218, Christian Schulte L07, 2009-11-18

Character Type

25

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

ID1218, Christian Schulte L07, 2009-11-18

Boolean Type

26

Boolean type

 constants bool true and false

Rather late addition!

 watch out for int with zero as false and any other value true!

ID1218, Christian Schulte L07, 2009-11-18

Constants

27

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

ID1218, Christian Schulte L07, 2009-11-18

Operators, Expressions, Statements

28

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

ID1218, Christian Schulte L07, 2009-11-18

Operators and Expressions

29

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!

ID1218, Christian Schulte L07, 2009-11-18

Operators and Expressions

30

No guarantee on shift a << b

 can be either arithmetic or logic

 arithmetic

 logic

-1 << 1 remains negative

-1 << 1 is positive

ID1218, Christian Schulte L07, 2009-11-18

Conditionals

31

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)

ID1218, Christian Schulte L07, 2009-11-18

Loops

32

As in Java, along with break and continue

ID1218, Christian Schulte L07, 2009-11-18

Unitialized Variables

33

Variables not by guarantee initialized

 unless global or static (later)

Always give initial value

 important for objects (later)

ID1218, Christian Schulte L07, 2009-11-18

Typecasts for Primitive Types

34

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

ID1218, Christian Schulte L07, 2009-11-18

Static Casts

35

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!

ID1218, Christian Schulte L07, 2009-11-18

Type Definitions

36

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

ID1218, Christian Schulte L07, 2009-11-18

37

Functions

ID1218, Christian Schulte L07, 2009-11-18

Function Definition

38

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

ID1218, Christian Schulte L07, 2009-11-18

Function Example

39 int maxx(int x, int y) { return (x > y) ? x : y;

}

ID1218, Christian Schulte L07, 2009-11-18

Function Invocation

40

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

ID1218, Christian Schulte L07, 2009-11-18

Function Overloading

41

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

ID1218, Christian Schulte L07, 2009-11-18

Function Declarations

42

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

ID1218, Christian Schulte L07, 2009-11-18

Default Parameters

43

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

ID1218, Christian Schulte L07, 2009-11-18

Inline Functions

44

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

ID1218, Christian Schulte L07, 2009-11-18

Separate Compilation

45

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)

ID1218, Christian Schulte L07, 2009-11-18

Header File maxx.h

46

/*

* Declaration of maximum function

*/ int maxx(int, int);

ID1218, Christian Schulte L07, 2009-11-18

Implementation File maxx.cpp

47

#include "maxx.h" int maxx(int x, int y) { return (x > y) ? x : y;

}

ID1218, Christian Schulte L07, 2009-11-18

Main File main.cpp

48

#include <iostream>

#include "maxx.h" int main() { std::cout << maxx(47,23)

<< std::endl; return 0;

}

ID1218, Christian Schulte L07, 2009-11-18

Putting Everything Together

49

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

ID1218, Christian Schulte L07, 2009-11-18

Include Each Header at Most Once

50

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 atmost-once inclusion

 define a preprocessor variable when included

 test whether preprocessor variable not already defined choose reasonably unique name

ID1218, Christian Schulte L07, 2009-11-18

Fixed Header File maxx.h

51

/*

* Declaration of maximum function

*/

#ifndef __MAXX_H__

#define __MAXX_H__ int maxx(int, int);

#endif

ID1218, Christian Schulte L07, 2009-11-18

Organizing Compilation

52

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

ID1218, Christian Schulte L07, 2009-11-18

53

Arrays

ID1218, Christian Schulte L07, 2009-11-18

C-style Arrays

54

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!

ID1218, Christian Schulte L07, 2009-11-18

Using Arrays as Parameters

55 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

ID1218, Christian Schulte L07, 2009-11-18

Using Arrays as Parameters

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

ID1218, Christian Schulte L07, 2009-11-18

Allocating Arrays

57

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

ID1218, Christian Schulte L07, 2009-11-18

Allocating Arrays

58

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)

ID1218, Christian Schulte L07, 2009-11-18

Primitive Arrays of Constants

59

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

ID1218, Christian Schulte L07, 2009-11-18

C-Style Strings

60

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)

ID1218, Christian Schulte L07, 2009-11-18

Vectors and C++ Strings

61

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

ID1218, Christian Schulte L07, 2009-11-18

62

Parameter Passing

ID1218, Christian Schulte L07, 2009-11-18

Call By-value

63

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

ID1218, Christian Schulte L07, 2009-11-18

Call By-reference

64

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

ID1218, Christian Schulte L07, 2009-11-18

Call By-reference

65

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

ID1218, Christian Schulte L07, 2009-11-18

66

Pointers: Outlook

ID1218, Christian Schulte L07, 2009-11-18

Pointers

67

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

ID1218, Christian Schulte L07, 2009-11-18

Pointers

68

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;

ID1218, Christian Schulte L07, 2009-11-18

Pointers Illustrated…

69

(&x) 100 x = 10

(&y) 104 y = 7

(&p) 200 p = ????

After declaration int x = 10;

 int y = 7; int* p; p points somewhere (unitialized)

ID1218, Christian Schulte L07, 2009-11-18

Segmentation Fault or Bus Error…

70

(&x) 100 x = 10

(&y) 104 y = 7

(&p) 200 p = ????

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

ID1218, Christian Schulte L07, 2009-11-18

Redirecting…

71

(&x) 100 x = 10

(&y) 104 y = 7

(&p) 200 p = &x = 100

Let p point to location of x p = &x;

ID1218, Christian Schulte L07, 2009-11-18

Assigning…

72

(&x) 100 x = 5

(&y) 104 y = 7

(&p) 200 p = &x = 100

Assign object pointed to by p a value

*p = 5;

ID1218, Christian Schulte L07, 2009-11-18

Redirecting…

73

(&x) 100 x = 5

(&y) 104 y = 7

(&p) 200 p = &y = 104

Let p point to location of y p = &y;

ID1218, Christian Schulte L07, 2009-11-18

Assigning…

74

(&x) 100 x = 5

(&y) 104 y = 99

(&p) 200 p = &y = 104

Assign object pointed to by p a value

*p = 99;

ID1218, Christian Schulte L07, 2009-11-18

Common Idioms

75

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

ID1218, Christian Schulte L07, 2009-11-18

Heap Memory Management

76

Get memory from heap int* p = new int;

 allocate memory block big enough for one int

After use, release delete p;

ID1218, Christian Schulte L07, 2009-11-18

Getting It Wrong

77

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

ID1218, Christian Schulte L07, 2009-11-18

What Is Next?

78

Storage classes

 automatic and static variables

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

ID1218, Christian Schulte L07, 2009-11-18

79

Summary

ID1218, Christian Schulte L07, 2009-11-18

Summary

80

Radically new computation model

 not type safe

 explicit memory management

Few guarantees

 primitive types and their operations

Memory management is very difficult!

ID1218, Christian Schulte L07, 2009-11-18

Download