L01 - Basic of C++

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 63

Basic of C++

Online References

C++ Online Reference http://www.cplusplus.com/reference/

http://www.cppreference.com/wiki/

SGI STL Programmers Guide http://www.sgi.com/tech/stl/ C++ Quick Reference Sheet http://www.sourcepole.ch/sources/programming/cpp/c ppqref.html Bjarne Stroustrup

What is C++?

A programming language developed by Bjarne Stroustrup Originally known as C with Classes Renamed to C++ in 1983 First commercial release in 1985 Main features: General purpose Object Oriented Compatibility with C

Hello World!
#include <iostream> using namespace std; int main () { cout << "Hello World !\n"; return 0; }

#include directive

The #include directive has two forms: For standard library headers, use #include <header> For user-defined header files, use #include "file-name" The user-defined header files will end with.h. The standard library headers do not end with .h. headers that starts with c are obtained from C library E.g., <cctype>, <cstdio>, <ctime>, <cstdlib>

Input and Output


Output using cout Input using cin To use either cin or cout, use the following two lines at the start of program #include <iostream> using namespace std;

The using Statement


A Namespace allows us to group classes, objects and functions under a given name. The C++ standard library put all classes, objects and functions within the namespace std. The line using namespace std; tells the compiler to make available all names in the namespace called std.

A Simple C++ Program


// L01p02.cpp #include <iostream> using namespace std; Declaring a constant const double PI = 3.14159; int main () { int radius; cout << "Enter a radius " ; Getting input cin >> radius; double area = PI * radius * radius; Declaring variable double circumference = 2 * PI * radius; anywhere cout << "Area is " << area << endl; cout << "Circumference is " << circumference << endl; return 0; }

Notation used in C++ lecture notes

Topics covered in the introduction are tagged with:


[new] topics introduced in C++, not valid in C [expanded] topics covered in C, but greatly expanded in depth in C++

Topics without tags are revision on basic language constructs valid in both C and C++

Control Statements

Program Execution Flow

Selection Statements - 1
if (a > b) { ... } else { ... }

if-else statement Valid comparison: boolean expression Primitive values (0 = false, nonzero = true)

// L01p03.cpp Output: #include <iostream> i:-1 d:2 using namespace std; d>i int main () { nonzero i is regarded as true int i = -1; double d = 2.0; nonzero d is regarded as true cout << "i:" << i << " d:" << d << endl; if ( d > i ) cout << "d > i" << endl; if ( i ) cout << "nonzero i is regarded as true" << endl; if ( d ) cout << nonzero d is regarded as true" << endl; return 0; }

11

Selection Statements - 2
switch (a) { case 1: ... break; case 2: case 3: ... default: }

switch-case statement

Variables in switch( ) must be integer type (or can be converted to integer) break : jump out of the switch block default : catch all unmatched cases

Optional

// L01p04.cpp #include <iostream> using namespace std; int main () { cout << "Enter your lab score: "; int score; cin >> score; switch (score) { case 10: cout << "Twoderful!!" << endl; break; case 9: case 8: cout << "Onederful!" << endl; break; case 7: case 6: cout << "Good" << endl; break; case 5: case 4: cout << "Can be better" << endl; break; case 3: case 2: case 1: case 0: cout << I should work harder" << endl; break; default: cout << "Invalid score" << endl; } return 0; } 12

Repetition Statements
while (a > b) { ... //body } do { ... //body } while (a > b);

while : check condition before

executing body

do-while: check condition after

executing body

A : initialization (e.g. int i = 0) B : condition (e.g. i < 10) C : update (e.g. ++i)

for (A; B; C) { ... //body }

Any of the above can be empty Execution order:

A, B, body, C, B, body, C
13

Declaration

Simple and composite data types

Primitive Data Types


Data Type
short unsigned short int unsigned int, size_t long unsigned long float double long double char signed char unsigned char bool

(Intel x86)
-32,768 through 32,787 0 through 65,535 -2,147,483,648 through 2,147,483,647 0 through 4,294,967,295 -2,147,483,648 through 2,147,483,647 0 through 4,294,967,295 Approximately 10-38 to 1038 with 7 digits of precision Approximately 10-308 to 10308 with 15 digits of precision Approximately 10-4932 to 104932 with 18 digits of precision The 7-bit ASCII characters -128 through 127 0 through 255 true or false
15

Variable Declaration

Form: type-name variable-name; type-name variable-name = initial-value; type-name variable-name(argument-list); type-name may be A primitive type or A user-defined (class) type. Example int i; double x = 5.5; double y(6.7); point p(x, y);

16

Automatic Type Conversion

If the operands are of different types, the following rules apply in this order:

If either operand is long double, convert the other to long double. If either operand is double, convert the other to double. If either operand is float, convert the other to float. If either operand is long, convert the other to long. Convert char and short to int

17

Explicit Type Conversion

An expression of one primitive type can be converted to another primitive type using the form:
new-type(expression)

Example

If i is an int and y a double


i = int(y);

will convert y to an int and store it in i. The statement:


i = y;

will do the same conversion.

18

Constant modifier

As prefix of data types E.g. const int i = 123; Constant must be initialized when declared and cannot be changed afterwards

19

Character Constants

The form 'c' The form '\x' called an escape sequence: \a alarm \\ backslash \b backspace \? question mark \f formfeed \' single quote \n newline \" double quote \r carrige return \ooo octal number \t horizontal tab \xhh hexadidecimal number \v vertical tab

20

C-String Constants

The form "sequence of characters" is called a C-string constant (or simply string constant). Note escape sequences may appear in the sequence of characters. String constants are stored as arrays of characters followed by a '\0'.

21

bool [new]

Boolean data

Can have the value true or false only Internally, true = 1, false = 0 Can be used in a condition Improve readability When an expression regarded as boolean data will be interpreted as true if it is non-zero or false otherwise

// L01p05.cpp #include <iostream> using namespace std; int main () { bool done = false; int i = 1; while (!done) { cout << "Solve q" << i << endl; if (i == 5) { done = true; } else { ++i; } } cout << done: << done << endl; system("pause"); return 0; } Solve q1 Solve q2 Solve q3 Solve q4 Solve q5 done:1
22

Enumeration

Enumeration allows the programmer to declare a new data type which takes specific values only
enum Color { Red, Yellow, Green };
Example Declaration Color c1, c2; c1 = Yellow; c2 = c1; Example Usage Color is a new data type

Values that are valid for a Color variable

Use of enumeration makes program more readable.


23

Enumeration in switch
Color myColor; // enum can be used in a switch statement switch (myColor) { case Red: ... case Yellow: ... case Green: ... } /* Symbols defined in enum are given integer values: By default, 1st symbol == 0, 2nd symbol == 1 etc. i.e. Red = 0, Yellow = 1, Green = 2 */ cout << "Green: " << Green << endl;

24

Operator Precedence
Rank Operator
1
[] () . -> ++ -++ -* & + ! ~ new * / % + << >>

Operation
Array subscript Function call Member access Member access Postfix increment or decrement Prefix increment or decrement Pointer de-referencing operator Address of operator Unary plus or minus Complement (logical) Bitwise complement Object creation Multiply, divide, remainder Addition, Subtraction Shift left Shift right

Associativity
Left

3 4 5

The smaller rank, the higher precedence


25

Operator Precidence (2)


Rank Operator
6 7 8 9 10 11 12 13 14
< <= > >= == != ! & ^ | && || ?: = *= /= &= += -= <<= >>= &= |=

Operation

Associativity

Less than, Less than or equal Greater than, Greater than or equal Equal to Not equal to Bitwise and Exclusive or Bitwise or Logical and Logical or Conditional Assignment Right Compound Assignment

26

Prefix and Postfix Increment


Prefix: ++x --x Postfix x++ x- Assume that i has the value 3. Then z = ++i; would result in both z and i having the value 4. But z = i++; would result in z having the value 3 and i the value 4.

27

The Conditional Operator


Form: boolean-expression ? value1 : value2 If the boolean-exression is true, then the result is value1 otherwise it is value2. Example: s = (score > 10? "true" : "false" ); In most cases the same effect can be achieved using the if-else statement. Example: The above conditional statement is equivalent to if (score > 10) { s = "true";} else { s = " false";}

28

Array
An array is a collection of homogeneous data (data of the same type) To declare an array of 10 integers: int iA[10];
// L01p06.cpp #include <iostream> using namespace std; int main () { int iA[10]; iA[0] = 123; iA[9] = 456; iA[10] = iA[0] + iA[9]; cout << "iA[1]: " << iA[1] << endl; cout << "iA[-1]: " << iA[-1] << endl; cout << "iA[10]: " << iA[10] << endl; system("pause"); return 0; } iA[1]: 2009145456 iA[-1]: 16 iA[10]: 579 Note: 1. Array entries contain garbage unless they are initialized explicitly 2. Array index out of bound error is not checked

29

sizeof( )

Use sizeof( ) to find the number of bytes taken by a variable (data type) during compilation.

// L01p07.cpp #include <iostream> using namespace std; int main () { int iA[] = {3,1,5,6,9,3,5,7,3,8,9,4,5,3,2,8,0}; cout << "sizeof(iA):" << sizeof(iA) << endl; // iA: variable name cout << " # of entries: " << sizeof(iA)/sizeof(int) << endl; // int: data type system("pause"); return 0; } sizeof(iA):68 # of entries in iA: 17 Note that sizeof() cannot be applied to an array parameter of a function.
30

Array Cannot Be Used In


int[10] someFunction( ) {...} Error: cannot return array

int ia[10], ib[10]; // Initialize array ib ia = ib;

Error: array assignment is invalid

31

Structure

A collection of data that can be of difference types


struct Person { char name[50]; int age; char gender; }; Person s1;

Declaring the structure called Person to store information about a persons name, age, and gender
s1 is a Person object

32

Use of a Structure
Person s1 = {"Potter", 13, 'm' }; Person s2; s2 = s1;
Declare & Initialize

Declare only

Structure assignment. Everything copied. Use . to access a field

s1.age = 14; s2.gender = 'f'; s2.age = s1.age * 2;

Read and store a field

33

Pointer

A pointer variable contains the address of another variable A pointer variable takes up 4 bytes
int x = 111; int *ptr; ptr = &x; *ptr = 123;

name

content

address

111 123

1024

Declare ptr as an int pointer &: address-of operator Dereference ptr ptr

1024

Note the different meanings of *


To declare a pointer To deference a pointer

34

NULL pointer

A null pointer points to nowhere and it has the value NULL. NULL is defined in <cstddef> as 0: When a pointer is regarded as a boolean, a null pointer is regarded as false, and a non-null pointer is regarded as true.

35

Pointer and const

const is used to prevent modification of a variable How does it work with pointers?

int i = 7; const int *p = &i; //int const *p = &i; *p = 8; i = 8; int * const q = &i; q = p; const int * const r = &i; *r = 8; Error r = p; Error

p points to an integer constant Are const int the same as int const? Error: cannot change constant

q is a constant pointer to int Error: cannot change constant pointer


r is a constant pointer to a constant integer

36

Pointers and Arrays

Array name is a constant pointer

ia 1032 1032 1036 3 5 11 7 9


1032 1036 1040 1024

Points to the first element (with index 0)

int ia[3] = {3, 5, 7}; int* ptr; ptr = ia; ptr[2] = 9; ptr = &ia[1]; ptr[1] = 11; ia = ptr;
ptr

Error
37

Pointer Arithmetic [expanded]

Pointer +n and pointer -n are valid expressions

int ia[5] = {1, 22, 3, 4, 5}; int* p = ia; int *q, *r; q = p + 4; r = q 1; cout cout Cout cout cout << << << << << //what is q? //what is r? 1 5 4 2 22

ia p q r 1040 1040 1056 1052 1 22 3 4 5


1024 1028 1032 1036 1040 1044 1048 1052 1056
38

*p << endl; *q << endl; *r << endl; *p + 1 << endl; *(p + 1) << endl;

Pointer Arithmetic [expanded]

Two forms of element access for arrays:


Using [ ], i.e. indexing Using pointer arithmetic


Using indexing

int ia[5] = {1, 2, 3, 4, 5}; for (int i = 0; i < 5; i++) cout << ia[i] << endl;

int ia[5] = {1, 2, 3, 4, 5}; int *ptr; for (ptr = ia; ptr != ia+5; ptr++) cout << *ptr << endl; Using pointer arithmetic

39

Pointer and Structure


Pointer can point to a structure
int main() { Person s = { "Potter", 13, 'm' }; Person *q; //Person Pointer

struct Person { char name[50]; int age; char gender; };


name s age

'P' 13 14 'm'

1024 1076 1080

q = &s;

gender

(*q).age = 14; q->age = 14; }

Equivalent Statements

1024
40

Dynamic Memory Allocation : new [new]


Up to now, pointers are used to point to existing (declared) variable Actually, new memory storage can be allocated at runtime Using the new keyword Syntax: new datatype where datatype can be Predefined data type: int, float User defined data type: enum, structure or class Address of the start of the allocated memory is returned by new and it is stored in a pointer variable

41

new : Single Element


name content address

int main() { int x = 123; int *p, *q; p = &x; q = new int;

x p q

123
1024

1024

123
1024 3000

1024

p q

New Memory Box

3000

42

Memory Leak
int main() { int x = 123; int *p, *q; p = &x; q = new int; q = p; }

x p q

123
1024 3000 1024

1024

Memory Leak!

3000

q is the only variable storing the address of the new memory box at 3000 If q is changed, the address of the new memory box is gone and the memory box cannot be accessed even though it is there. This is known as memory leak

43

new : Array of elements

An array can be allocated dynamically

The size can be supplied at run time



ia

int main() { int size; int *ia; cout << Enter size:; cin >> size; ia = new int[size]; ia[0] = ... ia[1] = ... }

Assume size = 5
44

new : Structure

Dynamic allocation for structure can be done similarly

int main() { Person *p; p = new Person; At this point


name


Memory space for 52 chars

p->age = 14; }
age gender

14

45

Releasing memory to system : delete


Objects created using the new operator can only be destroyed using the delete operator. Syntax: delete pointer delete [ ] pointer_to_array Note: Delete is to deallocate the memory pointed by the pointer. Delete is not used to deallocate the pointer Dereferencing pointer after delete will produce unpredictable result! Using delete instead of delete[] to delete an array will produce unpredictable result.

46

delete : An example
/* PERSON: a structure defined before*/ int main() { Person *p; p = new Person;
p

NULL 14
Free memory

p->age = 14;

delete p; p = NULL;

Good Practice: Always set a pointer to NULL after delete

// many other statements p->age = 15; }


47

Error!

References [new]

A reference variable is a pointer that is automatically dereferrenced when it is used. Example: int x; int *p = &x; // p points to the int x int & rx = x; // rx is also pointing to the int x Difference between the usage of p and rx: To decrement x, we use --x To decrement x through p, we use --*p To decrement x through rx, we use --rx Same syntax as x, as if rx is an alternate name (synonym) of the int x. No need to dereferrence rx
48

Reference Examples
name content

int x = 456; int& intRef = x; intRef++; cout << x << endl;


Output: 457 intRef x

456

int& intRef1;

Error: must initialize

int i; int& ref = &i; Error: ref is not an ordinary


pointer expected by &i

49

Function

Function

A function is a named block of statements with parameters Syntax Return-type function-name( parameters ) { // body } The function gets its input from the caller through parameters When // body is done, the result of Return-type is returned When the block { } is replaced by ;, we have the corresponding function prototype // Function definition Return-type: int int factorial( int n){ Function-name: factorial int result = 1, i; Parameters: int n for (i = 2; i <= n; i++) Function prototype: result *= i; int factorial(int n); return result; }
51

Function Prototype (Declaration)


int factorial( int );
Function prototype

int main( ) { cout << factorial(9) << endl; } int factorial(int n) { int result = 1, i; for (i = 2; i <= n; i++) result *= i; return result; }
Actual Implementation

52

Function : Default Argument [new]


Function parameter can be given a default value. Default value is used if the caller does not supply a value

Default value

double logarithm( double N, double base = 10 ) } { ... Calculates Logbase(N) ... int main( ) { cout << logarithm(1024.,2) << endl; //Log2(1024.) cout << logarithm(1024.) << endl; //Log10(1024.) }
Make use of default
53

Function : Default Argument [new]

Parameters with default values should appear last in the parameter list

E.g. f(int i, int j = 123, int k = 456) But not f(int i, int j = 123, int k) Only trailing arguments can be omitted E.g. Given f(int i, int j = 123, int k = 456)
f(999); f(999, 888); f(999, , 777); //ok. Equal to f(999, 123, 456) //ok. Equal to f(999, 888, 456) //compilation error

When calling a function that has default parameters



54

Function : Argument Passing

There are three ways of passing an argument into a function: 1. Pass by value 2. Pass by address (or Pass by pointer ) 3. Pass by reference Lets try to define a function swap(a, b) to swap the parameters a and b

55

Function : Pass by value


void swap_ByValue( int a, int b ){ int temp; temp = a; a = b; b = temp; } int main() { int i = 123, j = 456; swap_ByValue(i, j); cout << i << endl; cout << j << endl; }
123 456
temp

i j 123 456

a b

123 456 456 123 123


56

Function : Pass by address/pointer


void swap_ByAdr( int* a, int* b ) { int temp; temp = *a; *a = *b; *b = temp; } int main() { int i = 123, j = 456; swap_ByAdr(&i, &j); cout << i << endl; cout << j << endl; }
456 123
temp

i j 123 456 456 123


1024 1028

a b

1024 1028 123


57

Function : Pass by reference [new]


void swap_ByRef( int& a, int& b ) { int temp; temp = a; a = b; b = temp; } int main() { int i = 123, j = 456; swap_ByRef(i, j); cout << i << endl; cout << j << endl; }
456 123 a b i j 123 456 456 123

temp

123
58

Pass by const reference


Objects may occupy big memory space and thus pass by value is inefficient. By declaring the parameter to be a const reference, the function can access the object directly but can not change it.

59

Example of const reference


int count_occurences(char c, const string& s) { int count = 0; for (int i = 0; i < s.size(); i++) { if (s[i] == c) count++; } return count; }

60

Function Signature [new]

Compiler recognizes a function by its function signature which includes Function name + data types of parameters Example: factorial(int) sqrt(double)

Note: Function return type is not part of the function signature

61

Function Overloading [new]


C++ allows multiple functions to have the same name provided their function signatures are different. This feature is called function overloading Besides having the same function name, the numbers and/or types of the parameters of these functions are different

62

Function Overloading [new]


int maximum(int a, int b) { if (a > b) return a; else return b; } int maximum (int a, int b, int c) { return max( max(a, b), c); } float maximum(float a, float b) { if (a > b) return a; else return b; } //Ver.1 // maximum(int, int)

//Ver.2 // maximum(int , int , int)

//Ver.3 // maximum(float , float )

maximum function has been overloaded Note the difference in number and data type of parameters
63

You might also like