C++ - Functions(9)

Embed Size (px)

Citation preview

  • 8/7/2019 C++ - Functions(9)

    1/60

  • 8/7/2019 C++ - Functions(9)

    2/60

    INTRODUCTION

    A function is a group of statements thattogether perform a task.

    You can divide up your code into separate

    functions. How you divide up your code among different

    functions is up to you, but logically the divisionusually is so each function performs a specific

    task.Example:A program that performs arithmeticcalculations, one function obtains user input,another function performs the calculation, and

  • 8/7/2019 C++ - Functions(9)

    3/60

    INTRODUCTION

    a third function performs output of the result.

    There are advantages to dividing the codeinto separate functions in addition to making

    the code easier to understand.Example: If a function performs a specific task,such as sending output to a printer, which isperformed several times in a program, you onlyneed to write once in a function the code

    necessary to send output to the printer, and thencall that function each time you need to performthat task.

  • 8/7/2019 C++ - Functions(9)

    4/60

    DEFINING AND CALLING A

    FUNCTION Implementing any function in addition to

    main involves two steps:

    Defining the function Calling the function

  • 8/7/2019 C++ - Functions(9)

    5/60

    DEFINING AND CALLING A

    FUNCTION Terminology of a Function#include

    main()

    {cout

  • 8/7/2019 C++ - Functions(9)

    6/60

    DEFINING AND CALLING A

    FUNCTION The function header consists of a return

    type, a function name, and an argument

    list.

    The data type intpreceding main is the return

    type, main is the function name, and the

    parentheses(), empty but not always, contains

    the argument list.

    A function header always is followed by an

    open curly brace, which begins the function

    body.

  • 8/7/2019 C++ - Functions(9)

    7/60

    DEFINING AND CALLING A

    FUNCTION The function body ends with a close curly

    brace.

    The function body consists of one or more

    statements.

    The last statement is a return statement.

    The function body must contain a return statement

    unless the return type is void, in which case the

    return statement is optional.

    The function header and body together are

    referred to as the function definition.

  • 8/7/2019 C++ - Functions(9)

    8/60

    DEFINING AND CALLING A

    FUNCTION A function cannot execute until it is first defined.

    Once defined, a function executes when it is

    called.

    A function is called through code. The main function is the exception.

    The main function is called automatically when

    your programs begins to run.

  • 8/7/2019 C++ - Functions(9)

    9/60

    DEFINING AND CALLING A

    FUNCTION Defining a Function#include

    void printMessage (void)

    {cout

  • 8/7/2019 C++ - Functions(9)

    10/60

    DEFINING AND CALLING A

    FUNCTION The function is defined first. The voidkeyword preceding the function name

    means that this function does not return a value.

    The voidkeyword in parentheses following the

    function name means this function has no arguments. The parentheses also could be left empty, such as after

    main; empty parentheses following the function name in a

    function header is the same as placing the voidkeyword

    within the parentheses.

    The function body does not need to contain an explicit

    return statement because, since the return type is

    void, the return statement is implied.

  • 8/7/2019 C++ - Functions(9)

    11/60

    DEFINING AND CALLING A

    FUNCTIONvoid printMessage (void)

    {

    cout

  • 8/7/2019 C++ - Functions(9)

    12/60

    DEFINING AND CALLING A

    FUNCTION Calling a Function Unless the function is called, it is there in the

    program, but it doesnt do anything.

    printMessage ( );

    printMessage is the called function, since it is thefunction being called from main.

    The empty parentheses indicate that no argumentsare being passed to this function.

    The order of execution: Execution always starts with the main function.

    The first statement in main,printMessage(), is executed.

  • 8/7/2019 C++ - Functions(9)

    13/60

    DEFINING AND CALLING A

    FUNCTION Execution next shifts to theprintMessage() function, andbegins with the first statement in that function.

    After theprintMessage function completes executing,

    execution returns to the main function with the next

    unexecuted statement, return 0, which completes themain function.

  • 8/7/2019 C++ - Functions(9)

    14/60

    DEFINING AND CALLING A

    FUNCTION Prototyping Since execution always starts with main, it seems

    more logical to place the main function first,ahead of a function.

    #include int main()

    {

    printMessage;

    return 0;

    }

    void printMessage (void){

    cout

  • 8/7/2019 C++ - Functions(9)

    15/60

    DEFINING AND CALLING A

    FUNCTION The code will not compile. The call in main to afunction will be highlighted, with the compiler errormessage being undeclared identifier.

    When the compiler, going from top to bottom in the code,

    encounters a function call, it must already know of thefunctions name, return type, and arguments. Which isnot a problem when the function was defined above themain function.

    One solution is to define all functions above main. Makes the code difficult to read.

    In a program with many functions, the mainfunction often acts as a switchboard, calling onefunction after another.

  • 8/7/2019 C++ - Functions(9)

    16/60

    DEFINING AND CALLING A

    FUNCTION The solution of preference is toprototype eachfunction, except main, which does not have to beprototyped since it is required by every program.

    #include

    void printMessage (void);

    int main()

    {

    printMessage;

    return 0;

    }

    void printMessage (void){

    cout

  • 8/7/2019 C++ - Functions(9)

    17/60

    DEFINING AND CALLING A

    FUNCTION The prototype is above all function definitions. It ensures that the compiler, compiling the code

    from top to bottom, will encounter the prototype

    before any function. The prototype is similar to a function header. The

    primary difference is that it has a semicolon at the

    end because it is a statement. By contrast, a

    function header must not be followed by a

    semicolon.

  • 8/7/2019 C++ - Functions(9)

    18/60

    VARIABLE SCOPE AND

    LIFETIME All variables have been defined at the top

    of the main function.

    In programs where the only function is main,those variables can be accessed throughout

    the entire program since main is the entire

    program.

    However, once the code is separated intofunctions, issues arise concerning variable

    scope and lifetime.

  • 8/7/2019 C++ - Functions(9)

    19/60

    VARIABLE SCOPE AND

    LIFETIME Local Variables You can call the same function multiple times.

    However, once the code is separated into

    functions, issues arise concerning variablescope and lifetime.

    #include

    void printMessage(void);

    int main()

    {

    int times = 0;

    char choice;

  • 8/7/2019 C++ - Functions(9)

    20/60

    VARIABLE SCOPE AND

    LIFETIMEdo {

    cout > choice;

    if (choice == Q)

    cout

  • 8/7/2019 C++ - Functions(9)

    21/60

    VARIABLE SCOPE AND

    LIFETIMEtimes ++;

    cout

  • 8/7/2019 C++ - Functions(9)

    22/60

    VARIABLE SCOPE AND

    LIFETIME#include

    void printMessage(void);

    int main()

    {

    char choice;

    do {

    cout > choice;

    if (choice == Q)

    cout

  • 8/7/2019 C++ - Functions(9)

    23/60

    VARIABLE SCOPE AND

    LIFETIMEreturn 0;

    }

    void printMessage (void)

    {

    int times = 0;

    times ++;

    cout

  • 8/7/2019 C++ - Functions(9)

    24/60

    VARIABLE SCOPE AND

    LIFETIME

    Variables have a lifetime.

    A variables lifetime begins when it is declared.

    A variables lifetime ends when it goes out of

    scope.

    Being a local variable in a function, each time

    the function is called, the variable is created,

    and each time the function ends, the variable

    is destroyed.

    There are two alternative methods to having

    the value of a variable persist between

    function calls.

  • 8/7/2019 C++ - Functions(9)

    25/60

    VARIABLE SCOPE AND

    LIFETIME

    One is to make the variable global rather than

    local.

    The other is to keep the variable local but make it

    static.

  • 8/7/2019 C++ - Functions(9)

    26/60

    VARIABLE SCOPE AND

    LIFETIME

    Global Variables

    A variable may be globalinstead of local.

    The term global means that the variable hasscope throughout the program.

    Since the variable has scope throughout the

    program, its lifetime does not end until the program

    ends.

    To make a variable global, it must be declared

    above all function definitions, generally with

    function prototypes.

  • 8/7/2019 C++ - Functions(9)

    27/60

    VARIABLE SCOPE AND

    LIFETIME#include

    void printMessage(void);

    int times;

    int main()

    {

    times = 0;char choice;

    do {

    cout > choice;

    if (choice == Q)

    cout

  • 8/7/2019 C++ - Functions(9)

    28/60

    VARIABLE SCOPE AND

    LIFETIMEprintMessage();

    } while (choice != Q);

    return 0;

    }

    void printMessage (void)

    {

    times ++;

    cout

  • 8/7/2019 C++ - Functions(9)

    29/60

    VARIABLE SCOPE AND

    LIFETIME

    The fact that a global variable can be accessed

    and changed anywhere in the program makes it

    more difficult to determine why a global variable

    has an invalid value than if the variables scope

    was far more limited.

    One alternative is to make the variable static.

  • 8/7/2019 C++ - Functions(9)

    30/60

    VARIABLE SCOPE AND

    LIFETIME Static Local Variables

    A variables lifetime was dictated by its scope. Since a local variables scope was limited to the

    function in which it was declared, the localvariables lifetime ended when that function ended.

    Since a global variable had scope throughout aprogram, the global variables lifetime did not enduntil the entire program ended.

    A static local variable is different. A static local variable has the scope of a local

    variable but the lifetime of a global variable.

  • 8/7/2019 C++ - Functions(9)

    31/60

    VARIABLE SCOPE AND

    LIFETIME A static local variable is declared exactly like

    a local variable, within a function rather than

    above all functions as with a global variable.

    The difference between the declaration of astatic local variable and a nonstatic, or

    automatic, local variable is that a static local

    variable is declared with the statickeyword,

    and usually also with a starting value.int times; local and global declaration

    static int times = 0; static local declaration

  • 8/7/2019 C++ - Functions(9)

    32/60

    VARIABLE SCOPE AND

    LIFETIME#include

    void printMessage(void);

    int times;

    int main()

    { char choice;

    do {

    cout > choice;if (choice == Q)

    cout

  • 8/7/2019 C++ - Functions(9)

    33/60

    VARIABLE SCOPE AND

    LIFETIMEprintMessage();

    } while (choice != Q);

    return 0;

    }

    void printMessage (void)

    {static int times = 0;

    times ++;

    cout

  • 8/7/2019 C++ - Functions(9)

    34/60

    SENDING INFORMATION TO A

    FUNCTION#include

    #include

    void printMessage(void);

    string str;

    int main()

    { cout > str;

    printMessage ( );

    return 0;

    }

    void printMessage ( ){

    cout

  • 8/7/2019 C++ - Functions(9)

    35/60

    SENDING INFORMATION TO A

    FUNCTION

    The parentheses following the function

    name in the function header contain the

    functions argument.

    Arguments are information that is provided

    to a function so that it may perform its

    task.

  • 8/7/2019 C++ - Functions(9)

    36/60

    SENDING INFORMATION TO A

    FUNCTION

    Passing Arguments by Value The content of the message to be output is

    passed to the function as an argument.

    #include #include

    void printMessage(string);

    int main()

    {

    string str;cout > str;

    printMessage (str );

  • 8/7/2019 C++ - Functions(9)

    37/60

    SENDING INFORMATION TO A

    FUNCTION

    return 0;

    }

    void printMessage (string s)

    {

    cout

  • 8/7/2019 C++ - Functions(9)

    38/60

    SENDING INFORMATION TO A

    FUNCTION

    The Function Prototype and Header

    Both the function prototype and the functionheader have one argument.

    The functions prototypes argument just hasthe arguments data type, whereas thefunction headers argument has both a datatype and an argument name.

    The function prototype may include anargument name as well as data type.

    void printMessage (string someArg);

  • 8/7/2019 C++ - Functions(9)

    39/60

    SENDING INFORMATION TO A

    FUNCTION

    However, the argument is called a dummy

    argumentbecause it serves no purpose.

    By contrast, the function headers argument

    must include an argument name as well as adata type.

  • 8/7/2019 C++ - Functions(9)

    40/60

    SENDING INFORMATION TO A

    FUNCTION

    Using the Function ArgumentprintMessage (str);

    void printMessage (string s)

    The function header must include anargument name as well as a data type so thevalue which is being passed by the functioncall may be stored in a variable that can beused in the function.

    The argument name in the function headercan be the same as the name of the variablepassed in the function argument.

  • 8/7/2019 C++ - Functions(9)

    41/60

    SENDING INFORMATION TO A

    FUNCTION

    printMessage (str);

    void printMessage (string str)

  • 8/7/2019 C++ - Functions(9)

    42/60

    SENDING INFORMATION TO A

    FUNCTION Using Multiple Function Arguments

    A function may have two or even more functionarguments.

    #include

    #include void printMessage(string, string);

    int main()

    {

    string name1, name2;

    cout > name1;cout > name2;

  • 8/7/2019 C++ - Functions(9)

    43/60

    SENDING INFORMATION TO A

    FUNCTIONprintMessage (name1, name2);

    return 0;

    }

    void printMessage (string firstName, string lastName)

    {

    cout

  • 8/7/2019 C++ - Functions(9)

    44/60

    SENDING INFORMATION TO A

    FUNCTION The consequences of a lack of correspondence between

    the order of arguments in the function call and the order ofthe arguments in the function header is more drastic whenthe multiple function arguments have different data types.

    #include

    #include void printMessage(string, int);

    int main()

    {

    string name;

    int age;

    cout > name1;cout > name2;

  • 8/7/2019 C++ - Functions(9)

    45/60

    SENDING INFORMATION TO A

    FUNCTIONcout > name;

    cout > age;

    printMessage(name, age);return 0;

    }

    void printMessage (string theName, int theAge)

    {

    cout

  • 8/7/2019 C++ - Functions(9)

    46/60

  • 8/7/2019 C++ - Functions(9)

    47/60

    SENDING INFORMATION TO A

    FUNCTIONcin >> num;

    doubleIt(num);

    cout

  • 8/7/2019 C++ - Functions(9)

    48/60

    SENDING INFORMATION TO A

    FUNCTION In order for the called function to change the

    value in main of a variable passed to it, thevariable must be passed by reference.

    The variable in the called function is called a

    reference variable. The reference variable is not a copy of the

    variable in main. Instead, the reference variable isan alias for the variable in main.

    In order to pass a variable by reference, the data

    type in the argument, both in the function headerand in the prototype, is followed by anampersand.

  • 8/7/2019 C++ - Functions(9)

    49/60

    SENDING INFORMATION TO A

    FUNCTION#include

    void doubleIt(int&);

    int main()

    {

    int num;cout > num;

    doubleIt(num);

    cout

  • 8/7/2019 C++ - Functions(9)

    50/60

  • 8/7/2019 C++ - Functions(9)

    51/60

    SENDING INFORMATION TO A

    FUNCTION Whether the program passes an argument in a

    function call by value or by reference is dictatedby the functions prototype.

    Can pass multiple values by reference as well asby value.

    Indeed, you can pass some values by reference andothers by value.

    You pass by reference those values you need tochange, and you pass by value those values you arenot changing.

    Note: There is another difference between passingbyvalue and passingby reference. You can pass byvalue expression andconstants as wellas variables. However, you can only pass variables by reference.

  • 8/7/2019 C++ - Functions(9)

    52/60

    SENDING INFORMATION TO A

    FUNCTION#include

    void addNumbers(int, int, int&);

    int main()

    {

    int firstNum, secondNum, sum = 0;

    cout > firstNum;

    cout > secondNum;

    addNumbers(firstNum, secondNum, sum);

    cout

  • 8/7/2019 C++ - Functions(9)

    53/60

    SENDING INFORMATION TO A

    FUNCTION

    void addNumbers(int x, int y, int& z)

    {

    z = x + y;

    }

  • 8/7/2019 C++ - Functions(9)

    54/60

    RETURNING A VALUE FROM A

    FUNCTION Arguments are used to pass values to a

    called function.

    A return value can be used to pass a valuefrom a called function back to the functionthat called it.

    #include

    int addNumbers(int, int);

    int main()

    {

    int firstNum, secondNum, sum = 0;cout > firstNum;

  • 8/7/2019 C++ - Functions(9)

    55/60

    RETURNING A VALUE FROM A

    FUNCTIONcout > secondNum;

    sum = addNumbers(firstNum, secondNum);

    cout

  • 8/7/2019 C++ - Functions(9)

    56/60

    RETURNING A VALUE FROM A

    FUNCTION

    The return value is added by indicating its

    data type in front of the function name in

    both the function prototype and header.

    The function call is on the right side of the

    assignment operator. To the left of the

    assignment operator is a variable of the

    same data type as the return value of thefunction.

  • 8/7/2019 C++ - Functions(9)

    57/60

    RETURNING A VALUE FROM A

    FUNCTION The body of the called function has the return

    keyword followed by a value of the data typecompatible with the function prototype andheader.

    The functions return value is the value thatfollows the return keyword.

    It is common that a function returning a valueis called on the right side of an assignment

    operator with a variable on the left side of theassignment operator to capture the returnvalue.

  • 8/7/2019 C++ - Functions(9)

    58/60

    RETURNING A VALUE FROM A

    FUNCTION

    However, this is not required.

    sum = addNumbers (firstNum, secondNum);

    cout

  • 8/7/2019 C++ - Functions(9)

    59/60

    RETURNING A VALUE FROM A

    FUNCTION

    If you are going to use a return value more

    than once, its generally a good idea to

    store that return value in a variable.

    This is typically done by calling the function

    on the right side of an assignment operator

    with a variable on the left side of the

    assignment operator to capture the returnvalue.

  • 8/7/2019 C++ - Functions(9)

    60/60

    RETURNING A VALUE FROM A

    FUNCTION

    While multiple values can be passed to a

    function as arguments, at this point,

    multiple values cannot be returned from

    functions using the data types.