Professional Documents
Culture Documents
L01 - Basic of C++
L01 - Basic of C++
L01 - Basic of C++
Online References
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>
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;
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.
[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
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);
executing body
executing body
A : initialization (e.g. int i = 0) B : condition (e.g. i < 10) C : update (e.g. ++i)
A, B, body, C, B, body, C
13
Declaration
(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
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
An expression of one primitive type can be converted to another primitive type using the form:
new-type(expression)
Example
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
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
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
27
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
31
Structure
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
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
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
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
36
int ia[3] = {3, 5, 7}; int* ptr; ptr = ia; ptr[2] = 9; ptr = &ia[1]; ptr[1] = 11; ia = ptr;
ptr
Error
37
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
*p << endl; *q << endl; *r << endl; *p + 1 << endl; *(p + 1) << endl;
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
'P' 13 14 'm'
q = &s;
gender
Equivalent Statements
1024
40
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
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
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
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
Memory space for 52 chars
p->age = 14; }
age gender
14
45
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;
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
456
int& intRef1;
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
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
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
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
54
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
i j 123 456
a b
a b
temp
123
58
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
60
Compiler recognizes a function by its function signature which includes Function name + data types of parameters Example: factorial(int) sqrt(double)
61
62
maximum function has been overloaded Note the difference in number and data type of parameters
63