5. TCB2073 - Lecture 5

download 5. TCB2073 - Lecture 5

of 44

description

zurina_musa

Transcript of 5. TCB2073 - Lecture 5

  • TCB2073 - SPDB

    Functions

  • 2

    Objectives

    To be able to implement functions

    To become familiar with the concept of parameter passing

    To develop strategies for decomposing complex tasks into simpler ones

    To be able to determine the scope of a variable

    To recognize when to use value and reference parameters

  • 3

    Introduction to Function

    Divide and conquer

    Construct a program from smaller pieces or

    components

    Each piece more manageable than the

    original program

  • 4

    More about Function

    Programs written by combining new functions with prepackaged functions in the

    C++ standard library.

    The standard library provides a rich collection of functions.

    Functions are invoked by a function call A function call specifies the function name and

    provides information (as arguments) that the called function needs

    Boss to worker analogy: A boss (the calling function or caller) asks a worker

    (the called function) to perform a task and return (i.e. report back) the results when the task is done.

  • 5

    Calling a Function

    A programmer calls a function

    to have its instructions executed.

    the caller (getting things done)

    the function (has the modify temperature instructions)

  • 6

    Types of Function

    Predefined Function: The use of C++

    standard library function

    pow(2,3)

    sqrt(4.0)

    User-defined Function: Programmers

    create function to organize/divide tasks

    in a program

  • 7

    Calling a Function

    Execution flow

    during a

    function call

  • 8

    Parameters

    When another function calls the pow function, it provides inputs, such as the values 2 and 3 in the call pow(2, 3).

    In order to avoid confusion with inputs that are provided by a human user (cin >>), these values are called

    parameter values.

    The output that the pow function computes is called the return value (not output using

  • 9

    Implementing Functions

    When writing this function, you need to:

    Pick a good, descriptive name for the function

    Give a type and a name for each parameter. There will be one parameter for each piece of information the function needs to do its job.

    Specify the type of the return value

    double cube_volume(double side_length)

  • 10

    Implementing Functions

  • 11

    User-Defined Functions

    1.Value-returning functions: have a return type

    Return a value of a specific data type using the return statement

    2.Void functions: do not have a return type

    Do not use a return statement to return a value

  • 12

    return Statement

    Once a value-returning function computes the value, the function returns this value via the return

    statement

    It passes this value outside the function via the return statement

  • 13

    Syntax: return Statement

    The return statement has the following syntax: In C++, return is a reserved word

    When a return statement executes Function immediately terminates Control goes back to the caller

    When a return statement executes in the function main, the program terminates

  • 14

    Value-Returning Functions

    To use these functions you must:

    Include the appropriate header file in your program

    Know the following items:

    1. Name of the function

    2. Number of parameters, if any

    3. Data type of each parameter

    4. Data type of the value returned: called the type of the function

  • 15

    Format for function definition:

    Return-value-type Function-name ( Parameter-list ) { variable declarations

    .

    return expression }

    Example:

    float square( int y, float z)

    {

    return y * z;

    }

    Function header

    Function body

    parameter-list for a function

    declaration takes the form of:

    type var_1, type var_2,

    Braces

    Value-Returning Functions

  • 16

    int add(int b, int c);

    int main(){

    int a = add(3,4);

    cout

  • 17

    int add(int b, int c);

    int main()

    {

    cout

  • 18

    int add(int , int, float);

    int main()

    {

    cout

  • 19

  • 20

  • 21

    Function Prototype (continued)

  • 22

    Functions Without Return Values

    Void Functions

    Consider the task of writing a string with the following format around it. Any string could be used.

    For example, the string "Hello" would produce:

    -------

    !Hello!

    -------

  • 23

    Void Functions

    void box_string(string str)

    Use a return type of void to indicate that a function does not

    return a value.

    void functions are used to

    simply do a sequence of instructions

    They do not return a value to the caller.

  • 24

    void box_string(string str)

    {

    int n = str.length();

    for (int i = 0; i < n + 2; i++){ cout

  • 25

    #include

    using namespace std;

    void prt (int); //Function prototype

    int main ( )

    { int X = 12; //Defines the integer variable

    prt ( X ); //Calls prt ( ) and passes it X

    return 0; // Returns 0 to the environment

    }

    void prt (int Y) //The prt ( ) function definition

    {

    cout

  • 26

    void add(int,int,float);

    int main()

    {

    add(3, 1, 2.3);

    return 0;

    }

    void add(int b,int c,float d)

    {

    cout

  • 27

    Variable Scope

    You can only have one main function

    but you can have as many variables and parameters

    spread amongst as many functions as you need.

    Can you have use the same name in different functions?

  • 28

    Variable Scope

    A variable or parameter that is defined within a function

    is visible from the point at which it is defined until

    the end of the block named by the function.

    This area is called the scope of the variable.

  • 29

    Variable Scope

    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

  • 30

    Variable Scope

    double cube_volume(double side_len)

    {

    double volume = side_len * side_len * side_len;

    return volume;

    }

    int main()

    {

    double volume = cube_volume(2);

    cout

  • 31

    Variable Scope

    Names inside a block are called local to that block.

    A function names a block.

    Recall that variables and parameters do not exist after the

    function is overbecause they are local to that block.

    But there are other blocks.

  • 32

    However, you can define another variable

    with the same name in a nested block.

    double withdraw(double balance, double amount)

    {

    if (...)

    {

    double amount = 10;

    ...

    }

    ...

    }

    a variable named amount local to the ifs block and a parameter variable named amount.

    Variable Scope Nested Blocks

  • 33

    Variable Scope Nested Blocks

    The scope of the parameter variable amount is

    the entire function, except the nested block.

    Inside the nested block, amount refers to the

    local variable that was defined in that block.

    You should avoid this potentially confusing

    situation in the functions that you write, simply by

    renaming one of the variables.

    Why should there be a variable

    with the same name in the same function?

  • 34

    Global Variables

    Global variables are defined outside any block. They are visible to every function defined after them.

    Generally, global variables are not a good idea.

    But

    heres what they are and how to use them

    (if you must).

  • 35

    Global Variables

    In some cases, this is a good thing: The header defines these global variables: cin cout

    This is good because there should only be one of each of these and every function who needs them should have direct access to them.

  • 36

    Global Variables

    int balance = 10000; // A global variable

    void withdraw(double amount)

    {

    if (balance >= amount)

    {

    balance = balance - amount;

    }

    }

    int main()

    {

    withdraw(1000);

    cout

  • 37

    Global Variables Just Say No

    You should avoid global variables in your programs!

  • 38

    Function Overloading

    Having functions with same name and different parameters Should perform similar tasks ( i.e., a function to square

    ints, and function to square floats).

    int square(int x) {return x * x;}

    float square(float x) { return x * x; }

    Program chooses function by signature

    - signature determined by function name and parameter types

    Can have the same return types

  • 39

    1

    2// Using overloaded functions

    3#include

    4

    5

    6

    7

    8int square( int x ) { return x * x; }

    9

    10double square( double y ) { return y * y; }

    11 12 int main()

    13 {

    14 cout

  • 40

    Parameters: Reference & Values

    Call by value

    Copy of data passed to function

    Changes to copy do not change original

    Used to prevent unwanted side effects

    Call by reference

    Function can directly access data

    Changes affect original

    Reference parameter for argument

    & is used to signify a reference

    void change(int &variable){ variable += 3; }

    Adds 3 to the variable inputted

    int y = &x.

    A change to y will now affect x as well

  • 41

    Is like passing the address of variable used as argument in function call.

    (Example next slide)

    Passing by reference

    Suppose you would like a function to get the users last name and ID number.

    The variables for this data are in your scope. But you want the function to change them for you.

    If you want to write a function that changes the value

    of a parameter, you must use a reference parameter.

  • 42

    int main()

    {

    int id;

    string name;

    getData(id,name);

    cout

  • 43

    void swap(int &px, int &py)

    {

    int temp;

    temp = px;

    px = py;

    py = temp;

    } int main()

    {

    int a = 10, b = 20;

    swap(a,b);

    cout

  • 44

    Summary

    Understand the philosophy of Functions

    Functions Constructs

    Function Definitions Function Header (Return-value-type, Function-name,

    Parameter-list)

    Function Body

    Function Prototypes

    Function Calls

    A local variable and global variable

    Function Overloading

    Pass-by-value VS. Pass-by-reference