Calling a Function

download Calling a Function

of 35

Transcript of Calling a Function

  • 8/9/2019 Calling a Function

    1/35

    Functions

  • 8/9/2019 Calling a Function

    2/35

  • 8/9/2019 Calling a Function

    3/35

    Calling a Function

    Execution flowduring a

    function call

    3

  • 8/9/2019 Calling a Function

    4/35

    An Output Statement Does Not Return a Value

    NOTE: output !return

    If a caller needs the result of a calculation done by

    a function, the function musthave a returnstatement.

    cout

  • 8/9/2019 Calling a Function

    5/35

    The Black Box Concept

    ! How did thepowfunction do its job?! You dont need to know.

    ! You only need to know itsspecification (name,

    parameters and return type).

    5

  • 8/9/2019 Calling a Function

    6/35

  • 8/9/2019 Calling a Function

    7/35

    Implementing Functions

    7

  • 8/9/2019 Calling a Function

    8/35

    Parameter Passing

    1. In the calling function, the local variable result1already exists. When the cube_volumefunction iscalled, the parameter variable side_lengthis created.

    double result1 = cube_volume(2);

    8

  • 8/9/2019 Calling a Function

    9/35

    Parameter Passing

    2. The parameter variable is initialized with the value thatwas passed in the call. In our case, side_lengthis setto 2.

    double result1 = cube_volume(2);

    9

  • 8/9/2019 Calling a Function

    10/35

    Parameter Passing

    3. The function computes the expression side_length *side_length * side_length, which has the value 8.That value is stored in the local variable volume.

    [inside the function]double volume = side_length * side_length * side_length;

    10

  • 8/9/2019 Calling a Function

    11/35

    Parameter Passing

    4. The function returns, at which point all of its variables

    are removed.

    The return value is transferred to the caller, that is, the

    function calling the cube_volumefunction, and storedin the variable in the body of that callerdouble result1 = cube_volume(2);

    The function executed: return volume;which gives the caller the value 8

    side_lengthand volumeare gone.

    11

    8

  • 8/9/2019 Calling a Function

    12/35

    Functions Without Explicit Return Values

    Consider the task of writing a string with the wrap-format around it.

    For example, the string "Hello"would produce:-------

    !Hello!-------

    12

  • 8/9/2019 Calling a Function

    13/35

    Functions Without Return Values The voidType

    voidas a return type, indicates that a functiondoes not return an actual value (of any type) to the caller.

    13

    Two important thingsabout functions of a voidtype:

    1.

    In the body of the function, theres no need for a return statement

    2.

    In the body of the caller, canNOTuse an assignment statement

    to invoke it;- Hence, we simply invoke it by its name in a given line

  • 8/9/2019 Calling a Function

    14/35

    Good Design Keep Functions Short

    ! There is a certain cost for writing a function:

    ! You need to design, code, and test the function.

    ! The function needs to be documented.! You need to spend some effort to make the function reusable

    rather than tied to a specific context.

    14

  • 8/9/2019 Calling a Function

    15/35

  • 8/9/2019 Calling a Function

    16/35

    Variable Scope

    16

    RULE:Avariable or parameter that is definedwithin a given function,isvisible from the point at which it is defined until

    the end of the block named by the function.

    This area is called the scopeof the variable.

    The scope of a variable is the part of the program in which it is visible.

    Because scopes do not overlap, a name in one scope cannot conflict with any

    name in another scope.

    A name in one scope is invisible in another scope

  • 8/9/2019 Calling a Function

    17/35

    Variable Scope Example

    double cube_volume(double side_len)

    {

    double volume = side_len * side_len * side_len;

    return volume;

    }

    int main()

    {

    double volume = cube_volume(2);

    cout

  • 8/9/2019 Calling a Function

    18/35

    More on Scopes

    18

    On the other hand:

    The following is NOT legal:

    int test(double volume)

    {

    double volume = cube_volume(2);

    double volume = cube_volume(10);

    // ERROR:cannot define another volume variable// ERROR: or parameter in the same scope

    ...

    }

  • 8/9/2019 Calling a Function

    19/35

    More on Scopes Nested Blocks

    One can define another variable

    with the same name in a nested block.

    double withdraw(double balance, double amount)

    {

    if (...){

    double amount = 10;...

    }

    ...

    }

    19

    amountlocal to the ifblock

    amountis overridden inside the if block

  • 8/9/2019 Calling a Function

    20/35

    Special Scope: Global Variables

    Global variables are declared outside of the function definitionsin a cpp file

    In general, they are not a good idea.

    However, sometimes, we simply must!

    20

    ! Since they are outside of every block!they are

    visible inside of each and every block!available

    for use in that block;

  • 8/9/2019 Calling a Function

    21/35

    Global Variables

    In some cases, this is a good thing:

    The header defines these global variables:

    cin

    cout

    21

  • 8/9/2019 Calling a Function

    22/35

    Global Variables Another Setting

    int balance = 10000; // A global variable

    void withdraw(double amount)

    {

    if (balance >= amount)

    {balance = balance - amount;

    }

    }

    int main()

    {

    withdraw(1000);

    cout

  • 8/9/2019 Calling a Function

    23/35

    Global Variables Breaking Open the Black Box

    Programs with global variables are difficult to maintain because you can nolonger view each function as a black box that simply receives parametervalues and returns a result or does something.

    When functions modify global variables, it becomes more difficult to understandthe effect of function calls.

    23

    You should avoidglobalvariables in your programs!

  • 8/9/2019 Calling a Function

    24/35

    Another PROBLEM

    Consider a function that simulates withdrawing a given amount ofmoney from a bank account, provided that sufficient funds areavailable.

    If the amount of money is insufficient, a $10 penalty is deducted

    instead.

    The function would be used as follows:

    double harrys_account = 1000;withdraw(harrys_account, 100);

    // Now harrys_account is 900withdraw(harrys_account, 1000);

    // Insufficient funds.// Now harrys_account is 890

    24

  • 8/9/2019 Calling a Function

    25/35

    void withdraw(double balance, double amount){

    const int PENALTY = 10;if (balance >= amount){

    balance = balance - amount;}else{balance = balance - PENALTY;

    }}

    double harrys_account = 1000;withdraw(harrys_account, 100);

    // Now harrys_account is 900withdraw(harrys_account, 1000);// Insufficient funds.// Now harrys_account is 890

    But this doesnt work!!! (why?)

    25

  • 8/9/2019 Calling a Function

    26/35

  • 8/9/2019 Calling a Function

    27/35

    The local variables, consts, and value parameters are initialized.

    double harrys_account = 1000;

    withdraw(harrys_account, 100);

    void withdraw(double balance, double amount){

    const int PENALTY = 10;

    27

  • 8/9/2019 Calling a Function

    28/35

    NOTHING happens to

    harrys_balancebecause

    it is a separate variable

    (in a different scope)

    !

    else{balance = balance - PENALTY;

    }

    28

  • 8/9/2019 Calling a Function

    29/35

    The function call has ended.

    Local names in the function are gone and

    withdraw(harrys_account, 100);

    NOTHING happened to harrys_balance.

    29

  • 8/9/2019 Calling a Function

    30/35

    Reference Parameters

    A reference parameter refers to a variable

    that is supplied in a function call.

    refers means that during the execution of the function, thereference parameter name is another name for the callers

    variable.

    This referring is how a functioncan change non-local variables (i.e., ones that are defined and/

    or used in the outer scope of the callee):

    changes to its local parameters names cause changes to thecallers variables they refer to.

    30

  • 8/9/2019 Calling a Function

    31/35

    Reference Parameters

    To indicate a reference parameter,

    you place an &after the type name.

    To indicate a usual (aka value) parameter,

    you do notplace an &after the type name.

    void withdraw(double&balance, double amount)

    31

  • 8/9/2019 Calling a Function

    32/35

    Reference Parameters

    The type double& is pronouned:

    reference to doubleor

    double ref

    32

  • 8/9/2019 Calling a Function

    33/35

    Reference Parameters

    The parameter namebalancerefers to thecallers variable named harrys_accountso thatchangingbalancechanges harrys_account.

    withdraw(harrys_account, 100);

    33

  • 8/9/2019 Calling a Function

    34/35

    Reference Parameters

    A reference parameter must always be called with a variable.

    i.e., you cant pass a constant value for a reference parameter it would be anerror

    withdraw(1000, 500);

    // Error: reference parameter must be a variable

    The reason is clearthe function modifies the reference parameter, but it is

    impossible to change the value of a constant number.

    34

    For the same reason, you cannot supply an expression:

    withdraw(harrys_account + 150, 500);

    // Error: reference parameter must be a variable

  • 8/9/2019 Calling a Function

    35/35

    When to use Reference Parameters???

    35

    ! Whenever a modification to more than one value is

    desired via a single function (reason: return can

    only return one single value)

    !

    Whenever there are LARGE objects that need to bemodified (passing them by-value will create an

    overhead of a memory space usage)