Cpp Lecture03

download Cpp Lecture03

of 36

Transcript of Cpp Lecture03

  • 7/30/2019 Cpp Lecture03

    1/36

    Type Cast Operator

    (type-name) expression // C notation

    type-name( expression) // C++ notation

    Ex. :

    average = sum/(float)i; // C notation

    average = sum/float(i); // C++ notation

    A type-name behaves as if it is a function for convertingvalues to a designated type.

  • 7/30/2019 Cpp Lecture03

    2/36

    Type Cast Operator C++ notation can be used only if the type is an identifier. For ex.,

    p = int *(q); // illegal

    In such case, use C notation

    p = (int *) q;

    OR,

    Use typedef,

    typedef int * int_pt;

    p = int_pt(q);

  • 7/30/2019 Cpp Lecture03

    3/36

    Type Cast Operator

    ANSI C++ adds following new cast operators :

    const_cast

    static_cast

    dynamic_cast

    reinterpret_cast

  • 7/30/2019 Cpp Lecture03

    4/36

    Expressions and Their Types

    An expression is a combination of operators, constants andvariables arranged as per the rules of the language.

    Expression may also include function calls which return

    values.

  • 7/30/2019 Cpp Lecture03

    5/36

    Expressions and Their TypesExpression Types

    Constant Integral Float Pointer Relational Logical Bitwise

    Expn. Expn. Expn. Expn. Expn. Expn. Expn.

    15 m x+y &m xb&&x=10 x>1

    x m*x 5+(float)10 ptr+1 m+n > 100

    5+int(2.0) 10.75

  • 7/30/2019 Cpp Lecture03

    6/36

    Special Assignment ExpressionsChained Assignment

    x = (y=10)

    or

    x = y = 10

    Cannot be used to initialize variables at the time ofdeclaration.

    For ex.,float a = b= 10.5; // wrong

    float a = 10.5, b=10.5; // Correct

  • 7/30/2019 Cpp Lecture03

    7/36

    Special Assignment Expressions

    Embedded Assignment

    identical to

    x = (y=50) + 10;

    y = 50;x = y + 10;

  • 7/30/2019 Cpp Lecture03

    8/36

    Special Assignment ExpressionsCompound Assignment

    Where, op = binary operator

    i.e.,

    Ex.,

    x = x + 10; can be written as x += 10;

    variable1 op= variable2;

    variable1 = variable1 op variable2;

  • 7/30/2019 Cpp Lecture03

    9/36

    Implicit conversion

    m = 5 + 2.75;

    For binary operator, if the operands type differ, thecompiler converts one of them to match with the other,using the rule that the Smaller type is converted to theWider type.

    Whenever a char or short int appears in an expressions, itis converted to an int. This is called integral wideningconversion.

    The implicit conversion is applied only after completing all

    integral widening conversion.

  • 7/30/2019 Cpp Lecture03

    10/36

    Implicit conversion :

    Water-fall model of type conversionshort char

    int

    unsigned

    long int

    unsigned long int

    float

    double

    long double

  • 7/30/2019 Cpp Lecture03

    11/36

    Control Structures

    Two way branch Multiple Branch Exit-control Entry-control

    Control Structure

    LoopSequenceSelection

    If-else switch do-while While, for

  • 7/30/2019 Cpp Lecture03

    12/36

    Control StructureEntry Entry Entry

    True False Loop

    True

    False

    Exit

    (a) Sequence (b) Selection (C) loop

    Action 1

    Action 2

    Action 3

    Action 1 Action 2

    Action 3

    Action 2

    Action 1

    Condition

    Condition

  • 7/30/2019 Cpp Lecture03

    13/36

    Control StructureForm 1

    If (expression is true){

    action 1;}action 2;action 3;

    Form 2

    If (expression is true){

    action 1;}Else{action 2;}

    action 3;

    switch (expression){

    case :{

    action 1;}case :{

    action 2;}case :{

    action 3;

    }default :{

    action 4;}

    }

    action-5;

  • 7/30/2019 Cpp Lecture03

    14/36

    Control Structure

    (a) do-while Statement (b) while statement (c) for statement

    do{

    action 1;}

    while(condition is true);action 2;

    while(condition is true){

    action 1;}action 2;

    for(initial value; test; inc/dec){

    action 1;}action 2;

  • 7/30/2019 Cpp Lecture03

    15/36

    Function in C++

  • 7/30/2019 Cpp Lecture03

    16/36

    Function: Introduction Group of statements that perform task Advantage :

    To reduce the size of a program by calling and using them at different places inthe program.

    void show(); /* Function declaration*/

    main(){

    .show(); /* Function call*/.

    }void show() /* Function definition*/{

    /* Function body*/

    }

  • 7/30/2019 Cpp Lecture03

    17/36

    The Main Function C C++ Main() does not return main() returns a value of

    any value type int to the operating system

    main() int main();{ int main(int argc, char *argv[]);

    //main prog. Stmt.}

    ORint main()

    void main() {

    { //main prog. Stmt. ...

    } return 0;}

    OS test Return value : zero ---- program ran successfullynonzero ---- there was a problem

  • 7/30/2019 Cpp Lecture03

    18/36

    Function Prototyping Prototype describes the function interface to the compiler by giving details such as the number

    and type of arguments and the type of return values. Function prototype is a declaration statement in the calling program. Function prototype is of the following form:

    Where,

    argument-list contains types and names of arguments that must be passed to the function

    Ex.,float volume(int x, float y, f loat z);

    float volume(int x, float y, z); // illegal

    In function declaration, name of arguments are dummy variables and therefore they are optional.That is, the form

    float volume(int, float, float); // valid

    Compiler checks for type of arguments when function is called. Therefore, if names are used ,they dont have to match the names used in the function call or function definition.

    type function-name(argument-list) ;

  • 7/30/2019 Cpp Lecture03

    19/36

    Function Prototyping In Function definition, names are required because the arguments

    must be referenced inside the function.Ex.,

    float cube(float, float, float)int main(){

    float b,w,h,cube;cin>>b>>w>>h;cube=volume(b,w,h); // Function call & b,w,h = Actual argu.

    }float volume(float a, float b, float c) // a,b,c Formal Argument{

    float v=a*b*c;.. /* Function Definition*/return v;

    }

  • 7/30/2019 Cpp Lecture03

    20/36

    Function Prototyping

    We can also declare a function with an empty argumentlist,

    void show();

    OR

    void show(void);

  • 7/30/2019 Cpp Lecture03

    21/36

    Call by ReferenceFunction Call by value Function Call by Reference In call by value method, the called function

    creates a new set of variables and copies thevalues of arguments

    #include#include

    void swap(int, int);void main(){int i=100, j=200;cout

  • 7/30/2019 Cpp Lecture03

    22/36

    Call by Reference In C, Call by Reference is done using pointer.

    void swap(int *m, int *n){

    int temp;temp=*m;

    *m=*n;*n=temp;

    }

    Function call:main(){

    int x=10,y=20; // print value of x and y before calling functionswap(&x, &y); // print value of x and y after calling function

    }

  • 7/30/2019 Cpp Lecture03

    23/36

    Return by Reference

    A function can also return a reference.Ex.,int &max(int &x, int &y){

    if (x > y)return x;

    elsereturn y;

    }

    Here, function call can appear on the left-hand side of anassignment statement.i.e.,

    max(a,b) = -1; // assigns -1 to a if it is larger, otherwise// -1 to b

  • 7/30/2019 Cpp Lecture03

    24/36

    Inline Functions Objective : to save memory space

    Every time, when function is called,-- jumping to function-- saving registers-- pushing arguments into the stack, and

    -- returning to the calling function If function is small, a substantial percentage of execution time

    may be spent.One Solution : Use Macro

    With Macro,

    Drawback : usual error checking does not occurduring compilationbecause,

    Macros are not really function

  • 7/30/2019 Cpp Lecture03

    25/36

    Inline Functions

    An Inline Function is a function that is expanded in linewhen it is invoked.

    That is,

    Compiler replaces the function call with the

    corresponding function code.

    Inline functions are defined

    as :

    Ex.inline function-header{

    function body}

    inline double volume(double a, double b,double c){

    return (a*b*c);

    }Int main(){

    double b,w,h,ans;ans=volume(b,w,h);cout

  • 7/30/2019 Cpp Lecture03

    26/36

    Inline Functions

    Situations where inline expansion may not work are :

    For functions returning values, if a loop, a switch, or agoto exists.

    For functions not returning values, if a return statementexists.

    If functions contain static variables.

    Ifinline functions are recursive.

  • 7/30/2019 Cpp Lecture03

    27/36

    Default Arguments

    C++ allows to call a function without specifying all itsarguments.

    A default argument is a value given in the functiondeclaration that the compiler automatically inserts if the

    caller does not provide a value for that argument in thefunction call.

    Default values are specified when the function is declared.

    Syntax :

    Ex.,

    float amount(float principal, int period, float rate=0.15);

    return_typefuncname(, type x = default_value,);

  • 7/30/2019 Cpp Lecture03

    28/36

    Default Arguments

    Ex.

    float amount(float principal, int period, float rate=0.15);

    Function call,

    value = amount(5000,7)

    value = amount(5000,5,0.12)

  • 7/30/2019 Cpp Lecture03

    29/36

    Default Arguments

    Only the trailing arguments can have default valuesand therefore we must add defaults from right to left.

    int mul(int i, int j=5, int k=10); // legal

    int mul(int i=5, int j, int k); // illegal

    int mul(int i=0, int j, int k=10); // illegal

    int mul(int i=2, int j=5, int k=10); // legal

  • 7/30/2019 Cpp Lecture03

    30/36

    Default Arguments#include float value(float p, int n, float r=0.15); // Prototype

    int main(){

    float amount;

    amount = value(5000.00,5);

    cout

  • 7/30/2019 Cpp Lecture03

    31/36

    Default Arguments Useful in situations where some arguments always have

    same value.

    Advantages :

    We can use default arguments to add new parameters tothe existing functions.

    Default arguments can be used to combine similarfunctions into one.

  • 7/30/2019 Cpp Lecture03

    32/36

    Function Overloading

    Overloading refers to use of the same thing for differentpurpose.

    That means,

    Use same function name to create functions thatperform a variety of different task is known asfunctionoverloading.

    Same function name but with different argument list.A function call first matches the prototype having the same

    number and type of arguments and then calls theappropriate function for execution.

  • 7/30/2019 Cpp Lecture03

    33/36

    Function OverloadingEx. :

    // Declaration

    int add(int a, int b); // Prototype 1

    int add(int a, int b, int c); // Prototype 2

    double add(double x, double y); // Prototype 3

    double add(int p, double q); // Prototype 4

    double add(double p, int q); // Prototype 5

  • 7/30/2019 Cpp Lecture03

    34/36

    Function Overloading A function call first matches the prototype having the same number and type

    of arguments and then calls the appropriate function for execution. A best match must be unique. The function selection involves the following steps :1. Find an exact match in which types of actual arguments are the same, and

    use that function.2. If an exact match is not found, the compiler uses the integral promotion to

    the actual argument, such aschar to intfloat to double

    3. When either of them fails, compile uses built-in conversion for uniquematch. If conversion is possible to have multiple matches, compiler willgenerate an error message.

    long square(long n)double square(double x)

    Function call,square(10)

    4. If all of the steps fail, then compiler will try the user-defined conversion +

    integral promotion + built-in conversion

  • 7/30/2019 Cpp Lecture03

    35/36

    Function Overloading// Declaration

    int add(int a, int b); // Prototype 1

    int add(int a, int b, int c); // Prototype 2

    double add(double x, double y); // Prototype 3

    double add(int p, double q); // Prototype 4

    double add(double p, int q); // Prototype 5

    // Function calls

    cout

  • 7/30/2019 Cpp Lecture03

    36/36

    Function Overloading#include

    int volume(int);double volume(double, int);

    long volume(long, int, int);

    int main(){

    cout