L01 - Basic of C++

download L01 - Basic of C++

of 63

Transcript of L01 - Basic of C++

  • 7/30/2019 L01 - Basic of C++

    1/63

    Basic of C++

  • 7/30/2019 L01 - Basic of C++

    2/63

    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

    2

    http://www.cplusplus.com/reference/http://www.cppreference.com/wiki/http://www.sgi.com/tech/stl/http://www.sourcepole.ch/sources/programming/cpp/cppqref.htmlhttp://www.sourcepole.ch/sources/programming/cpp/cppqref.htmlhttp://www.research.att.com/~bs/C++.htmlhttp://www.research.att.com/~bs/C++.htmlhttp://www.sourcepole.ch/sources/programming/cpp/cppqref.htmlhttp://www.sourcepole.ch/sources/programming/cpp/cppqref.htmlhttp://www.sgi.com/tech/stl/http://www.cppreference.com/wiki/http://www.cplusplus.com/reference/
  • 7/30/2019 L01 - Basic of C++

    3/63

    What is C++?

    A programming language developed by BjarneStroustrup

    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

    3

    http://www2.research.att.com/~bs/homepage.htmlhttp://www2.research.att.com/~bs/homepage.htmlhttp://www2.research.att.com/~bs/homepage.htmlhttp://www2.research.att.com/~bs/homepage.html
  • 7/30/2019 L01 - Basic of C++

    4/63

    Hello World!

    #include

    using namespace std;

    int main () {

    cout

  • 7/30/2019 L01 - Basic of C++

    5/63

    #include directive

    The #include directive has two forms:

    For standard library headers, use

    #include

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

    5

  • 7/30/2019 L01 - Basic of C++

    6/63

    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 using namespace std;

    6

  • 7/30/2019 L01 - Basic of C++

    7/63

    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 thenamespace called std.

    7

  • 7/30/2019 L01 - Basic of C++

    8/63

    A Simple C++ Program// L01p02.cpp

    #include using namespace std;

    const double PI = 3.14159;

    int main () {

    int radius;

    cout > radius;double area = PI * radius * radius;

    double circumference = 2 * PI * radius;

    cout

  • 7/30/2019 L01 - Basic of C++

    9/63

    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 expandedin depth in C++

    Topics without tags are revision on basic language

    constructs valid in both C and C++

    9

  • 7/30/2019 L01 - Basic of C++

    10/63

    Control Statements

    Program Execution Flow

  • 7/30/2019 L01 - Basic of C++

    11/63

    Selection Statements - 1 i f - el se statement

    Valid comparison: boolean expression

    Primitive values (0 = false, nonzero = true)

    if (a > b) {

    ...

    } else {

    ...

    }

    11

    // L01p03.cpp

    #include using namespace std;int main () {

    int i = -1; double d = 2.0;cout

  • 7/30/2019 L01 - Basic of C++

    12/63

    Selection Statements - 2

    swi t ch- case statement

    Variables in switch( ) must be integer

    type (or can be converted to integer) br eak : jump out of the switch block

    def aul t : catch all unmatched cases

    Optional

    switch (a) {

    case 1:

    ...

    break;

    case 2:

    case 3:

    ...

    default:}

    12

    // L01p04.cpp#include using namespace std;int main () {

    cout score;

    switch (score) {case 10:cout

  • 7/30/2019 L01 - Basic of C++

    13/63

    Repetition Statements

    whi l e : check condition before

    executing body

    while (a > b) {

    ... //body

    }

    do {

    ... //body

    } while (a > b);

    A : initialization (e.g. i nt i = 0)

    B : condition (e.g. i < 10)

    C : update (e.g. ++i )

    Any of the above can be empty

    Execution order:

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

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

    }

    13

    do- whi l e: check condition after

    executing body

  • 7/30/2019 L01 - Basic of C++

    14/63

    Declaration

    Simple and composite data types

  • 7/30/2019 L01 - Basic of C++

    15/63

    Primitive Data Types

    Data Type (Intel x86)

    short -32,768 through 32,787

    unsigned short 0 through 65,535

    int -2,147,483,648 through 2,147,483,647

    unsigned int,size_t 0 through 4,294,967,295

    long -2,147,483,648 through 2,147,483,647

    unsigned long 0 through 4,294,967,295float Approximately10-38 to 1038 with 7 digits

    of precision

    double Approximately10-308 to 10308 with 15

    digits of precision

    long double Approximately10-4932 to 104932 with 18digits of precision

    char The 7-bit ASCII characters

    signed char -128 through 127

    unsigned char 0 through 255

    bool true or false15

  • 7/30/2019 L01 - Basic of C++

    16/63

    Variable Declaration

    Form:

    type-namevariable-name;type-namevariable-name = initial-value;

    type-namevariable-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

  • 7/30/2019 L01 - Basic of C++

    17/63

    Automatic Type Conversion

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

    If either operand is long double, convert the otherto long double.

    If either operand is double, convert the other todouble.

    If either operand is float, convert the other tofloat.

    If either operand is long, convert the other to long. Convertchar and short to int

    17

  • 7/30/2019 L01 - Basic of C++

    18/63

    Explicit Type Conversion

    An expression of one primitive type can be

    converted to another primitive type using theform:

    new-type(expression)

    Example

    Ifi is an int and y a doublei = int(y);will convert y to an int and store it in i.

    The statement:i = y;

    will do the same conversion.

    18

  • 7/30/2019 L01 - Basic of C++

    19/63

    Constant modifier

    As prefix of data types

    E.g. consti nt i = 123;

    Constant must be initialized when declared andcannot be changed afterwards

    19

  • 7/30/2019 L01 - Basic of C++

    20/63

    Character Constants

    The form'c' The form'\x' called an escape sequence:\aalarm \\ backslash\b backspace \? question mark\f formfeed \' single quote

    \nnewline \" double quote\r carrige return \ooooctal number\thorizontal tab \xhh hexadidecimal number\v vertical tab

    20

  • 7/30/2019 L01 - Basic of C++

    21/63

    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 ofcharacters.

    String constants are stored as arrays of charactersfollowed by a '\0'.

    21

  • 7/30/2019 L01 - Basic of C++

    22/63

    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 asboolean data will be interpreted as trueif it is non-zero or false otherwise

    22

    // L01p05.cpp#include using namespace std;

    int main () {bool done =false;int i = 1;while (!done) {

    cout

  • 7/30/2019 L01 - Basic of C++

    23/63

    Enumeration

    Enumeration allows the programmer to declare anew data type which takes specific values only

    enumColor {

    Red, Yellow, Green

    };

    Color is a new data type

    Values that are valid for aColor variableExample Declaration

    Color c1, c2;

    c1 = Yellow;

    c2 = c1;

    Example Usage

    23

    Use of enumeration makes program more readable.

  • 7/30/2019 L01 - Basic of C++

    24/63

    Enumeration in switchColor myCol or ;

    / / enumcan be used in a switch statement

    swi t ch ( myCol or ) {case Red:

    . . .case Yellow:

    . . .case Green:

    . . .}

    /* Symbols defined in enumare given integer values:

    By default, 1stsymbol == 0, 2ndsymbol == 1 etc.

    i.e. Red = 0, Yellow = 1, Green = 2 */cout

  • 7/30/2019 L01 - Basic of C++

    25/63

    Operator PrecedenceRank Operator Operation Associativity

    1 [] Array subscript Left() Function call. Member access-> Member access

    ++ -- Postfix increment or decrement

    2 ++ -- Prefix increment or decrement*

    Pointer de-referencing operator& Address of operator+ - Unary plus or minus! Complement~ Bitwise complement

    new Object creation

    3 * / % Multiply, divide, remainder

    4 + - Addition, Subtraction

    5 > Shift right

    25

    The smaller rank, the higher precedence

    (logical)

  • 7/30/2019 L01 - Basic of C++

    26/63

    Operator Precidence (2)Rank Operator Operation Associativity

    6 < >= Greater than, Greater than or equal

    7 == Equal to! Not equal to

    8 & Bitwise and

    9 ^ Exclusive or

    10|

    Bitwise or11 && Logical and

    12 || Logical or

    13 ?: Conditional

    14 = Assignment Right*= /= &=

    += -= = &= |=

    Compound Assignment

    26

    !=

  • 7/30/2019 L01 - Basic of C++

    27/63

    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.

    Butz = i++;

    would result in z having the value 3 and i the value 4.

    27

  • 7/30/2019 L01 - Basic of C++

    28/63

    The Conditional Operator

    Form:

    boolean-expression?value1:value2

    If the boolean-exression is true, then the result is value1otherwise it is value2.

    Example:

    s =(score > 10? "true" : "false" );

    In most cases the same effect can be achieved using theif-else statement.

    Example: The above conditional statement is equivalent toif (score > 10) {s = "true";}

    else {s = " false";}

    28

  • 7/30/2019 L01 - Basic of C++

    29/63

    ArrayAn array is a collection ofhomogeneous data (data of

    the same type)To declare an array of 10 integers:

    int iA[10];

    29

    // L01p06.cpp#include using namespace std;int main () {

    int iA[10];iA[0] = 123;iA[9] = 456;

    iA[10] = iA[0] + iA[9];cout

  • 7/30/2019 L01 - Basic of C++

    30/63

    sizeof( )

    Use sizeof( ) to find the number of bytes taken by a

    variable (data type) during compilation.

    30

    // L01p07.cpp#include 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

  • 7/30/2019 L01 - Basic of C++

    31/63

    Array Cannot Be Used In

    i nt [ 10] someFunct i on( ) {. . . }

    i nt i a[ 10] , i b[ 10] ;/ / I ni t i al i ze ar r ay i b

    i a = i b;

    Error: cannot return array

    Error: array assignment isinvalid

    31

  • 7/30/2019 L01 - Basic of C++

    32/63

    Structure A collection of data that can be of difference types

    Declaring the structure called Personto store information

    about a persons name, age, and gender

    s1 is a Personobject

    structPerson {char name[50];

    int age;

    char gender;

    };

    Person s1;

    32

  • 7/30/2019 L01 - Basic of C++

    33/63

    Use of a Structure

    Person s1 = {"Potter", 13, 'm' };

    Person s2;

    s2 = s1;

    s1.age = 14;

    s2.gender = 'f';

    s2.age = s1.age * 2;

    Declare & Initialize

    Structure assignment. Everything copied.

    Use . to access a field

    Declare only

    Read and store a field

    33

  • 7/30/2019 L01 - Basic of C++

    34/63

    Pointer A pointer variable contains the

    address of another variable A pointer variable takes up 4 bytes

    111

    1024

    1024

    x

    addressname content

    ptr

    int x = 111;

    int *ptr;

    ptr = &x;

    *ptr = 123;

    Declare ptr as an int pointer

    &: address-of operator

    Dereference ptr

    Note the different meanings of*

    To declare a pointer

    To deference a pointer

    34

    123

  • 7/30/2019 L01 - Basic of C++

    35/63

    NULL pointer

    A null pointer points to nowhere and it has the value

    NULL. NULL is defined in 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

  • 7/30/2019 L01 - Basic of C++

    36/63

    Pointer and const const is used to prevent modification of a variable

    How does it work with pointers?

    i nt i = 7;

    const i nt *p = &i ;

    / / i nt const *p = &i ;

    *p = 8;

    i = 8;

    i nt * const q = &i ;

    q = p;

    const i nt * const r = &i ;

    *r = 8;

    r = p;

    p points to an integer constant

    Are const int the same as int const?

    Error: cannot change constant

    qis a constant pointerto int

    Error: cannot change constant pointer

    r is a constant pointerto a constant integer

    Error

    Error

    36

  • 7/30/2019 L01 - Basic of C++

    37/63

    Pointers and Arrays

    Array name is a constant pointer

    Points to the first element (with index 0)

    1032

    3

    1024

    1032

    5 1036

    7 1040

    iaint ia[3] = {3, 5, 7};

    int* ptr;

    ptr = ia;

    ptr[2] = 9;

    ptr = &ia[1];

    ptr[1] = 11;ia = ptr;

    37

    ptr 1032

    Error

    9

    1036

    11

  • 7/30/2019 L01 - Basic of C++

    38/63

    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; //what is q?

    r = q 1; //what is r?

    cout

  • 7/30/2019 L01 - Basic of C++

    39/63

    Pointer Arithmetic [expanded]

    Two forms of element access for arrays: Using [ ], i.e. indexing

    Using pointer arithmetic

    int ia[5] = {1, 2, 3, 4, 5};

    for (int i = 0; i < 5; i++)

    cout

  • 7/30/2019 L01 - Basic of C++

    40/63

    Pointer and Structure

    Pointer can point to a structure

    int main()

    {

    Person s =

    { "Potter", 13, 'm' };

    Person *q; //Person Pointer

    q = &s;

    (*q).age = 14;

    q->age = 14;

    }

    EquivalentStatements

    'P'

    13

    1024

    1076

    'm' 1080

    1024

    sage

    name

    gender

    q

    40

    struct Person {

    char name[50];

    int age;

    char gender;

    };

    14

  • 7/30/2019 L01 - Basic of C++

    41/63

    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 newkeyword

    Syntax:

    newdatatype

    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 returnedby new and it is stored in a pointer variable

    41

  • 7/30/2019 L01 - Basic of C++

    42/63

    new : Single Element

    int main()

    {

    int x = 123;

    int *p, *q;

    p = &x;

    q = new int;

    }

    x 123

    1024

    1024

    addressname content

    p

    q

    x

    3000

    1024

    1024123

    pq

    3000

    New Memory

    Box

    42

  • 7/30/2019 L01 - Basic of C++

    43/63

    Memory Leak

    q is the only variable storing the address of the new memory boxat 3000

    If q is changed, the address of the new memory box is gone andthe memory box cannot be accessed even though it is there. Thisis known as memory leak

    int main()

    {

    int x = 123;int *p, *q;

    p = &x;

    q = new int;

    q = p;

    }

    x

    3000

    1024

    1024123

    pq

    3000

    Memory

    Leak!

    43

    1024

  • 7/30/2019 L01 - Basic of C++

    44/63

    new : Array of elements

    An array can be allocated dynamically The size can be supplied at run time

    intmain()

    {

    int size;

    int *ia;

    cout > size;

    ia = new int[size];

    ia[0] = ...

    ia[1] = ...

    }

    ia

    Assume size = 5

    44

  • 7/30/2019 L01 - Basic of C++

    45/63

    new : Structure

    Dynamic allocation for structure can be done

    similarly

    intmain()

    {

    Person *p;

    p = new Person;

    p->age = 14;

    }

    At this point

    p

    age

    name

    gender

    Memoryspacefor 52

    chars

    45

    14

  • 7/30/2019 L01 - Basic of C++

    46/63

    Releasing memory to system : delete

    Objects created using the new operator can only be

    destroyed using the delete operator. Syntax:

    deletepointer

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

    Using delete instead of delete[] to deletean array will produce unpredictable result.

    46

    A

  • 7/30/2019 L01 - Basic of C++

    47/63

    delete : An example/* PERSON: a structure definedbefore*/

    intmain(){

    Person *p;

    p = new Person;

    p->age = 14;

    delete p;

    p = NULL;

    // many other statements

    p->age = 15;

    }

    p

    Good Practice:Always set a

    pointer to NULL after delete

    Error!

    Freememory

    47

    NULL

    14

  • 7/30/2019 L01 - Basic of C++

    48/63

    References [new]

    A reference variable is a pointer that is automatically

    dereferrencedwhen 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 dereferrencerx

    48

  • 7/30/2019 L01 - Basic of C++

    49/63

    Reference Examples

    x

    name content

    intRef 456

    int x = 456;

    int& intRef = x;

    intRef++;cout

  • 7/30/2019 L01 - Basic of C++

    50/63

    Function

  • 7/30/2019 L01 - Basic of C++

    51/63

    Function

    A function is a named block of statements with parameters

    SyntaxReturn-typefunction-name( parameters ) {

    // body

    }

    The function gets its input from the caller through parameters

    When // body is done, the result ofReturn-type is returned When the block { }is replaced by ;, we have the corresponding

    function prototype

    // Function definition

    intfactorial( int n){

    int result = 1, i;for (i = 2; i

  • 7/30/2019 L01 - Basic of C++

    52/63

    Function Prototype (Declaration)

    int factorial( int );

    int main( )

    {

    cout

  • 7/30/2019 L01 - Basic of C++

    53/63

    Function : Default Argument [new]

    Function parameter can be given a default value.

    Default value is used if the caller does not supply a value

    doubl e l ogar i t hm( doubl e N, double base = 10 ){ . . . Cal cul at es Logbase( N) . . . }

    i nt mai n( ){

    cout

  • 7/30/2019 L01 - Basic of C++

    54/63

    Function : Default Argument [new]

    Parameters with default values should appear last in

    the parameter list E.g. f ( i nt i , int j = 123, int k = 456)

    But not f ( i nt i , int j = 123, i nt k)

    When calling a function that has default parameters

    Only trailing arguments can be omitted

    E.g. Given f ( i nt i , int j = 123, int k = 456)

    f ( 999) ; //ok. Equal to f ( 999, 123, 456)

    f ( 999, 888) ; //ok. Equal to f ( 999, 888, 456)

    f ( 999, , 777) ; //compilation error

    54

    F i A P i

  • 7/30/2019 L01 - Basic of C++

    55/63

    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

    F i P b l

  • 7/30/2019 L01 - Basic of C++

    56/63

    Function : Pass by value

    void swap_ByValue( int a, int b ){

    int temp;

    temp = a;

    a = b;

    b = temp;

    }

    123

    456

    123

    456

    i

    j

    a

    b

    56

    int main()

    { int i = 123, j = 456;

    swap_ByValue(i, j);

    cout

  • 7/30/2019 L01 - Basic of C++

    57/63

    Function : Pass by address/pointervoid swap_ByAdr( int* a, int* b )

    { int temp;

    temp = *a;

    *a = *b;

    *b = temp;

    }

    123

    456

    1024

    1028

    1024

    1028

    i

    j

    a

    b

    57

    int main()

    { int i = 123, j = 456;

    swap_ByAdr(&i, &j);

    cout

  • 7/30/2019 L01 - Basic of C++

    58/63

    Function : Pass by reference [new]

    void swap_ByRef( int& a, int& b )

    { int temp;

    temp = a;

    a = b;

    b = temp;

    }

    123

    456

    i

    j

    a

    b

    58

    int main()

    { int i = 123, j = 456;

    swap_ByRef(i, j);

    cout

  • 7/30/2019 L01 - Basic of C++

    59/63

    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 notchange it.

    59

    E l f f

  • 7/30/2019 L01 - Basic of C++

    60/63

    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

    F i Si [ ]

  • 7/30/2019 L01 - Basic of C++

    61/63

    Function Signature [new]

    Compiler recognizes a function by its function signature

    which includesFunction name + data types of parameters

    Example:

    f act or i al ( i nt )

    sqr t ( doubl e)

    61

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

    F ti O l di [ ]

  • 7/30/2019 L01 - Basic of C++

    62/63

    Function Overloading [new]

    C++ allows multiple functions to have the same name

    provided their function signatures are different. Thisfeature is called function overloading

    Besides having the same function name, the numbersand/or types of the parameters of these functions aredifferent

    62

    F ti O l di [ ]

  • 7/30/2019 L01 - Basic of C++

    63/63

    Function Overloading [new]int maximum(int a, int b) //Ver.1{ // maximum(int, int)

    if (a > b) return a;else return b;

    }int maximum (int a, int b, int c) //Ver.2{ // maximum(int , int , int)

    return max( max(a, b), c);}float maximum(float a, float b) //Ver.3{ // maximum(float , float )

    if (a > b) return a;

    else return b;}

    maximumfunction has been overloaded

    Note the difference in number and data type of parameters