functions & parameter passing

Upload: brian-ellis

Post on 07-Jul-2018

228 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/18/2019 Functions & Parameter Passing

    1/56

     

    Functions & Parameter Passing

  • 8/18/2019 Functions & Parameter Passing

    2/56

     

    General vs. specialized functions

    • Suppose you had a function called drawSquare,which, when called, always produces the

    following output * * * ** * * *

    * * * *

    * * * *

    • !his is an e"ample of a very specialized function,since it is only capa#le of drawing a very specificfigure

  • 8/18/2019 Functions & Parameter Passing

    3/56

     

    $ general square function

    • %ontrast the previous e"ample with a similar functionthat taes an argument specifying the square's size(for e"ample, drawSquare)*+ would produce thefollowing output

    * *

    * *

    • $n even more general function might tae an

    argument specifying the character to draw with( fore"ample, drawSquare)*, -'+ would produce

    $ $

    $ $

  • 8/18/2019 Functions & Parameter Passing

    4/56

     

    Specifying function requirements

    • e can see that a more general function

    might require arguments( #ut how do we

    now what the requirements are/

    • $ general method for specifying the

    requirements for a function call is called

    function declaration or function prototyping  prototyping 

  • 8/18/2019 Functions & Parameter Passing

    5/56

     

    Function prototype

    • 0eclaration statement for function

    • Provides information necessary to call function

     1  0ata type of function's return value )if any+ 1  0ata type)s+ of any required argument)s+, listed in the

    order required this is called the parameter list  parameter list 

    • 2sually appears a#ove main)+ or in a header file

    • Function prototypes are declaration statements 1

    each one ends with a semicolon

  • 8/18/2019 Functions & Parameter Passing

    6/56

     

    Function prototype e"amples

    • !he function prototypes for some familiar

    functions are listed #elow

    int rand)+( 33 appears in the stdli#.h header file

    dou#le sqrt )dou#le+( 33 appears in math.h

    dou#le pow )dou#le, dou#le+( 33 also in math.h

  • 8/18/2019 Functions & Parameter Passing

    7/56 

    Function prototypes

    • $ function prototype includes the following parts 1  !he function's return type( can #e any data type, including

    void )meaning no return value+

     1  !he function name )must #e a valid %44 identifier 1 samerules apply for functions and varia#les+

     1  !he function's parameter list, which specifies the datatype of each required argument, and optionally includes a

    name for each parameter 

  • 8/18/2019 Functions & Parameter Passing

    8/56

     

    5"amples

    int rand)+(

    type of valuereturned

    name offunction

    parameter list

    dou#le pow )dou#le, dou#le+(

     6ote a function's parameter list may, #ut does

    not have to, include a name for each

     parameter( the parameters are not named in

    the e"amples a#ove

  • 8/18/2019 Functions & Parameter Passing

    9/56

     

    7ore e"amples

    • Previously, we considered 8 possi#le versions of a drawSquare

    function( the prototypes for each version are shown #elow

    void drawSquare)+(

    33 draws a 9"9 square made of asteriss

    void drawSquare)int+(

    33 draws a square of the specified size, made of asteriss

    void drawSquare)int size, char pi"el+(

    33 draws a square of the specified size using the specified33 picture element

    •  6ote that these are e"amples of overloaded functions 1 their

     prototypes differ only in their parameter lists

  • 8/18/2019 Functions & Parameter Passing

    10/56

     

    Function definition

    • $ function prototype merely declares a

    function, specifying requirements for a

    function call• $ function call invoes a function

    • $ function definition implementsimplements the

    function( that is, it contains the code thatwill #e e"ecuted when the function is called

  • 8/18/2019 Functions & Parameter Passing

    11/56

     

    Function definition

    • $ function definition has two parts

     1 !he heading, which supplies the same

    information as the function prototype 1 !he #ody, which implements the function

  • 8/18/2019 Functions & Parameter Passing

    12/56

     

    Function definition

    void drawSquare)+

    :

    for )int ";

  • 8/18/2019 Functions & Parameter Passing

    13/56

     

     6otes on function definition

    • $lthough the function's heading containsthe same information as the prototype, it

    appears in slightly different form 1 !here is no semicolon at the end of the function

    heading

     1 Bf there are any parameters, they must #e

    named, even if they were not named in the prototype( if they were named in the prototype,the names must match exactly

  • 8/18/2019 Functions & Parameter Passing

    14/56

     

    5"ample!he second drawSquare prototype didn't specify a name for

    its parameter( the function definition must provide a

     parameter name

    void drawSquare)int+( 33 prototype

    void drawSquare)int size+ 33 definition

    :

    for )int ";

  • 8/18/2019 Functions & Parameter Passing

    15/56

     

    5"ample!he third drawSquare function's prototype specified names

    for #oth parameters( the function definition must use e"actly

    the same names

    void drawSquare)int size, char pi"el+( 33 prototypevoid drawSquare)int size, char pi"el+ 33 definition

    :

    for )int ";

  • 8/18/2019 Functions & Parameter Passing

    16/56

     

    CalueDreturning functions

    • !he function definition e"amples we have seen so

    far have all #een void functions

    • $ valueDreturning function has an additionalrequirement in its definition( such a function must

    include a return statement

    • !he return statement specifies what value a

    function returns( this is the value that a function

    call represents when used in an e"pression

  • 8/18/2019 Functions & Parameter Passing

    17/56

     

    5"ample!he function #elow returns the cu#e of its argument

    dou#le cu#eBt )dou#le value+

    :

    dou#le cu#e(

    cu#e ; value ? value ? value(

    return cu#e(

    A

    $nother way to write the same function

    dou#le cu#eBt )dou#le value+

    :

    return value ? value ? value(

    A

  • 8/18/2019 Functions & Parameter Passing

    18/56

     

    Coid functions and return

    statements• 7ost void functions can #e written without

    return statements

    • Eowever, sometimes it's handy to #e a#le touse a return statement in a void function

    • Bf desired, the following statement can #e

    used in a void function

    return(

  • 8/18/2019 Functions & Parameter Passing

    19/56

     

    5"ample

    • Suppose you are writing a function that displays amenu of choices for the user, then performs someaction #ased on the user's choice

    • Bf the user chooses a valid menu item, a function iscalled to perform the chosen tas 

    • Bf an invalid item is chosen, or the user chooses toquit, the function returns without performing anyfurther action

    • !he ne"t slide shows an e"ample of such afunction

  • 8/18/2019 Functions & Parameter Passing

    20/56

     

    5"amplevoid doSomething)+

    :

    int choice ; get%hoice)+( 33 calls function that displays menu &

    switch)choice+ 33 gets user's preference

    : case

    drawSquare)+(

     #rea(

    case *

    draw%ircle)+(

     #rea(default

    return(

    A

    A

  • 8/18/2019 Functions & Parameter Passing

    21/56

     

    5"ample safe input of num#ers

    • e have already discussed the pro#lems involved

    with e"traction of numeric data in interactive

     programs 1  2ser can, accidentally or deli#erately, type #ad data

     1  hen #ad data are encountered, the input stream shuts

    down, and no more data can #e read

    • e have also seen an effective solution to this pro#lem( instead of reading num#ers directly, read

    characters and convert them to num#ers

  • 8/18/2019 Functions & Parameter Passing

    22/56

     

    Safe input e"ample!he code #elow provides a safe input method for a positive integer

    int num#er ;

  • 8/18/2019 Functions & Parameter Passing

    23/56

     

    Safe input e"ample

    • !he code on the previous slide is a good

    e"ample of a useful routine that we might

    want to use several times within a program• Iather than copy and paste this code

    wherever we need to input a num#er, we can

     Just encapsulate the code within a function,then call the function whenever we need to

    read a num#er 

  • 8/18/2019 Functions & Parameter Passing

    24/56

     

    Function definition placement

    • Function definitions can #e placed either #efore or

    after the main function in a program, #ut not

    within the #loc that defines main)+• Function prototypes should always appear #efore

    main)+, and #efore any other function definitions

    • Bf function definitions are placed a#ove main)+,

    then function prototypes may #e omitted( however,you need to now how to read and write

     prototypes, so it is good practice to use them

  • 8/18/2019 Functions & Parameter Passing

    25/56

     

    Eeader files

    • Functions are often written to #e generally

    useful

    • Bf a function wors well to solve a pro#lemin one program, it would pro#a#ly solve a

    similar pro#lem in a different program

    • !he use of header filesheader files can mae your codemore reDusea#le

  • 8/18/2019 Functions & Parameter Passing

    26/56

     

    Eeader files contain declarations,

    such as the following• function prototypes like double

    sqrt( double );

    • named constants like const intINT_MAX = !"#";

    • classes like

    strin$% ostream% istream• ob&ects like

    cin% cout 

  • 8/18/2019 Functions & Parameter Passing

    27/56

     

    Eeader files

    • Eeader files also contain documentation(

    for e"ample, each function prototype in a

    header file would #e accompanied #y acomment e"plaining what the function does

    • $ header file is a te"t file written in %44,

     #ut the file e"tension is .h instead of .cpp

  • 8/18/2019 Functions & Parameter Passing

    28/56

     

    Bmplementation files

    • hen header files contain function prototypes, acorresponding implementation fileimplementation file is required

    • !he implementation file contains the definition)s+of the function)s+ declared in the header file

    • !he implementation file has the same name as theheader file, #ut has a .cpp e"tension

    • $n implementation file can #e compiled, #ut it isnot a program, #ecause it doesn't contain a main)+function

  • 8/18/2019 Functions & Parameter Passing

    29/56

     

    2sing your own li#raries

    • !o create your own li#rary of functions,start #y placing your function prototype)s+

    in a header file• 0efine your function)s+ in an

    implementation file

    • rite your program, including main)+, in aseparate file

    • !he ne"t three slides illustrate this process

  • 8/18/2019 Functions & Parameter Passing

    30/56

     

    Eeader file

    • !he te"t of the file safenum.h is shown #elowKifndef S$F5627LE

    Kdefine S$F5627LE

    int get6um)+(33 Ieads and returns a num#er from the standard input stream( ignores

    33 e"traneous characters. Bf no digits are entered, returns <

    Kendif 

    • !he statements that start with the K character are

     preprocessor directives that indicate that the code #etweenthe Kifndef directive and the Kendif directive should only #eincluded in a program if it hasn't #een included already( this

     prevents a possi#le liner error 

  • 8/18/2019 Functions & Parameter Passing

    31/56

     

    Bmplementation file

    • !he implementation file contains the definition)s+ offunction)s+ declared in the header file( it should containany preprocessor directives needed for the function code,

    as well as a preprocessor directive indicating inclusion ofthe header file

    • Bn this e"ample, the synta" would #e

    Kinclude >safenum.h@

    • !his synta" assumes that the header file andimplementation file are in the same folder on your dis(if they are not, the full path to the file would need to #eincluded in the quoted string

  • 8/18/2019 Functions & Parameter Passing

    32/56

     

    Program file

    • !he program file would contain main)+, and wouldhave a name that is different from the header andimplementation files

    • $s well as any other necessary preprocessordirectives, the program file would need an includedirective for the new header( in this e"ample

    Kinclude >safenum.h@• $gain, the full path would #e necessary if theheader is in a different dis folder 

  • 8/18/2019 Functions & Parameter Passing

    33/56

     

    Mining your header files

    • !he process descri#ed in the last several slides is thecorrect one in the most general sense, independent ofany particular compiler or programming environment

    • Bn most B05s )such as dev or Cisual %44+, however,there is at least one additional step required to properly lin your header file, implementation fileand program 1 this involves creating a proJect file

    • !his is an environmentDspecific tas( it will varyaccording to which B05 you're using

  • 8/18/2019 Functions & Parameter Passing

    34/56

     

    Parameter passing methods

    • Bn all the function prototype and definitione"amples we have seen thus far, parameters arespecified as if they were simple varia#les, and the

     process of parameter passing is compara#le to the process of assigning a value to a varia#le 1  5ach parameter is assigned the value of its

    corresponding argument

     1  $lthough the value of a parameter may change duringthe course of a function, the value of the correspondingargument is not affected #y the change to the parameter 

  • 8/18/2019 Functions & Parameter Passing

    35/56

     

    Passing #y value

    • !he process descri#ed on the previous slide, andillustrated in all e"amples thus far, is called  passing passingby valueby value D thisD this is the default method for parameter

     passing• hen arguments are passed #y value

     1  a copycopy of each argument valuevalue is passed to its respective parameter 

     1  the parameter is stored in a separate memory location fromthe storage location of the argument, if the argument hasone

     1  $ny valid e"pression can #e used as an argument

  • 8/18/2019 Functions & Parameter Passing

    36/56

     

    5"ampleThe program below illustrates what happens when arguments are passed byvalue. A tracing of the changes in the program’s variables is shown on the right.

    int multiply (int, int);

    int main()

    {

    int a, b, c;

    a !;

    b ";

    c multiply(a,b);

    a multiply(b,c);

    return #;$

    int multiply (int %, int y)

    {

    % % & y;

    return %;$

    a b c % y

    ! " ! "

    '#

    '#

    "

    '#

    "#

    "#

    hen the program ends, the variables

    remaining in memory have the values

    shown in red

  • 8/18/2019 Functions & Parameter Passing

    37/56

     

    Mimitations of pass #y value

    • Iecall that a function can have either onereturn value or no return value

    • Bf we want a function's action to affect morethan one varia#le in the calling function, wecan't achieve this goal using return valuealone 1 remem#er, our options are one ornone

    • !he ne"t e"ample illustrates this pro#lem

  • 8/18/2019 Functions & Parameter Passing

    38/56

     

    5"ample 1 swap functionuppose we want to write a function that swaps two values* that is, value a isreplaced by value b, and value b is replaced by the original value of a. The function

    below is an attempt to achieve this goal.

    void swap (int %, int y)

    {

    int tmp %;% y;

    y tmp;

    $

    The function appears to wor+ correctly. The

    ne%t step is to write a program that calls the

    function so that we can test it*

    int main()

    {

    int a!, b;

    cout -- /efore swap, a0 -- a -- and b0

      -- b -- endl;swap(a,b);

    cout -- After swap, a0 -- a -- and b0

      -- b -- endl;

    return #;

    $

    1utput*/efore swap, a! and b

     After swap, a! and b

  • 8/18/2019 Functions & Parameter Passing

    39/56

     

    hat went wrong/

    • Bn the swap function, parameters " and y were passed the values of varia#les a and # via thefunction call swap)a, #+(

    • !hen the values of " and y were swapped• hen the function returned, " and y were no

    longer in memory, and a and # retained theiroriginal values

    • Iemem#er, when you pass #y value, the parameteronly gets a copy of the corresponding argument(changes to the copy don't change the original

  • 8/18/2019 Functions & Parameter Passing

    40/56

     

    Nuilding a #etter swap function

    introducing reference parameters• %44 offers an alternative parameterDpassing

    method called pass-by-reference pass-by-reference

    • hen we pass #y reference, the data #eing passedis the addressaddress of the argument, not the argument

    itself 

    • !he parameter, rather than #eing a separate

    varia#le, is a reference to the same memory thatholds the argument 1 so any change to the

     parameter is also a change to the argument

  • 8/18/2019 Functions & Parameter Passing

    41/56

     

    Ievised swap functione indicate the intention to pass by reference by appending an ampersand (2)to the data type of each reference parameter. The improved swap function

    illustrates this*

    void swap (int2 %, int2 y)

    {

    int tmp %;% y;

    y tmp;

    $

    The reference designation (2) means that % and

    y are not variables, but are instead references

    to the memory addresses passed to them

    3f we had the same main program as before, the

    function call*

    swap(a,b);

    indicates that the first parameter, %, is a

    reference to a, and the second parameter, y, isa reference to b

  • 8/18/2019 Functions & Parameter Passing

    42/56

     

    Eow passD#yDreference wors

    • Bn the e"ample on the previous slide, " and y referenced the samememory that a and # referenced

    • Iemem#er that varia#le declaration does two things

     1  $llocates memory )one or more #ytes of I$7, each of which has anumeric address+

     1  Provides an identifier to reference the memory )which we use instead ofthe address+

    • Ieference parameters are simply additional la#els that wetemporarily apply to the same memory that was allocated with the

    original declaration statement•  6ote that this means that arguments passed to reference

     parameters must #e varia#les or named constants( in other words,the argument must have its own address

  • 8/18/2019 Functions & Parameter Passing

    43/56

     

    5"ample4arlier, we loo+ed at a trace of the program below, on the left. The program

    on the right involves the same function, this time converted to a void functionwith an e%tra reference parameter.

    int multiply (int, int);

    int main()

    {

    int a, b, c;

    a !;

    b ";

    c c  multiply(a,b);

    a a  multiply(b,c);

    return #;

    $

    int multiply (int %, int y)

    {

    % % & y;

    return %;

    $

    void multiply (int, int, int2);

    int main()

    {

    int a, b, c;

    a !;

    b ";

    multiply(a,b,cc);

    multiply(b,c,aa);

    return #;

    $

    void multiply (int %, int y, int2 5)

    {

    5 % & y;

    $

  • 8/18/2019 Functions & Parameter Passing

    44/56

     

    2sing B3O stream o#Jects as

    arguments• e have seen at least one function that

    taes an input stream as one of its

    arguments getline• $s you now, getline taes two arguments

    an input stream o#Ject and a string varia#le

    • Nased on what you now now, what parameterDpassing method does getline usefor the string varia#le/

  • 8/18/2019 Functions & Parameter Passing

    45/56

     

    2sing B3O stream o#Jects as

    arguments• !he prototype for getline loos something lie

    this

    void getline)istream&, string&+(

    • !he stream varia#le, lie the string varia#le, is passed #y reference

    • Stream varia#les are always passed #y reference(

    you will get a compiler error if you attempt towrite a function with a value parameter of a streamtype

  • 8/18/2019 Functions & Parameter Passing

    46/56

     

    5"ampleThe following function opens an input file using the file name specified by the

    program’s user. ince the file stream is passed by reference, the file passed to

    the function will be open in both the current function and the calling function.

    bool open3nput6ile (ifstream2);

    77 attempts to open the input file specified by the user; returns true if open succeeds,

    77 false if open fails

    bool open3nput6ile (ifstream2 inf)

    {

    string file8ame;

    cout -- 4nter name of input file to open* 0;

    cin 99 file8ame;return inf.open(file8ame.c:str());

      77 c:str function converts string to format reuired by open()

    77 function returns the result of the attempt to open the file (true or false)

    $

  • 8/18/2019 Functions & Parameter Passing

    47/56

     

    7aing get6um more versatile

    • Previously, we e"amined a function that provided

    a >safe@ input mechanism for integer num#ers

    • !he function read a set of characters from thestandard input stream, converting digit characters

    into their int equivalents and accumulating an int

    result, which the function returned

    • !he function would #e more versatile if it couldread input from any input stream, not Just cin( a

    few minor modifications mae this possi#le

  • 8/18/2019 Functions & Parameter Passing

    48/56

     

    Ievisions to get6um?n’)

    {

    @ins.get(c);

    $

     77 s+ipping parts not changed

    return num;

    $

  • 8/18/2019 Functions & Parameter Passing

    49/56

     

    Scope of identifiers

    • !he part of a program where a specific identifiercan #e recognized is called the scopescope of theidentifier 

    • Scope in a program is similar to fame in the realworld 1  Bf scope is local local , then the identifier can only #e used

    within its local area( outside this area, the identifier isunnown. Mie me )and pro#a#ly you+, this identifieris not famous.

     1  Bf scope is global  global , the identifier can #e used anywherein the program, #ecause a glo#al identifier is >famous@

  • 8/18/2019 Functions & Parameter Passing

    50/56

     

    0etermining the scope of an

    identifier • !he scope of an identifier is determined #y

    the location of its declaration statement

    • $n identifier that is declared within a #loc)inside a function, for e"ample+ is local tothat #loc 

    •$n identifier that is declared outside any #loc is glo#al to the file in which it isdeclared

  • 8/18/2019 Functions & Parameter Passing

    51/56

     

    5"amples

    • !he following identifiers are typically declared inglo#al space 1  Function names

     1  6amed constants

    • Caria#les are almost always )you can forget a#out>almost@ for the duration of this course+ declaredlocally to functions

    • Some identifiers may #e more local yet( the controlvaria#le of a for loop is often declared at the #eginningof the loop( its scope is limited to the loop itself 

  • 8/18/2019 Functions & Parameter Passing

    52/56

     

    5"ampleetermine the scope of each identifier in the following program

    const double

  • 8/18/2019 Functions & Parameter Passing

    53/56

      8

    0etailed Scope Iules

    . Function namename has glo#al scope if declaredoutside any other function.

    *. Function parameter  parameter  scope is identical to scope

    of a local local  varia#le declared in the outermost #loc of the function #ody.

    8. Glo#al scope e"tends from declarationdeclaration to the

    end of the fileend of the file, e"cept as noted on the ne"tslide

  • 8/18/2019 Functions & Parameter Passing

    54/56

     

    0etailed scope rules, continued

    9. Mocal scope e"tends from declarationdeclaration to

    the end of the block end of the block  where identifier is

    declared. !his scope includes any nested #locs, e"cept as noted in rule .

    . $n identifier's scope does not does not  include any

    nested #loc that contains a locallydeclared identifier with the same name

    )local identifiers have name precedence+.

  • 8/18/2019 Functions & Parameter Passing

    55/56

     

    Eow %ompiler 0etermines Scope

    • hen an e"pression refers to an identifier, thecompiler first checs the local declarations.

    • Bf the identifier isn't local, compiler wors outward

    through each level of nesting until it finds anidentifier with same name. !here it stops.

    • $ny identifier with the same name declared at alevel further out is never reached.

    • Bf compiler reaches glo#al declarations and stillcan't find the identifier, an error message results. 

  • 8/18/2019 Functions & Parameter Passing

    56/56

     6ame Precedence

    )or 6ame Eiding+

    • hen a function declares a local identifier withthe same name as a glo#al identifier, the local

    identifier taes precedence within that function• So far as the code in the #ody of the function is

    concerned, the glo#al identifier doesn't e"ist( thelocal identifier taes precedence, effectively

    hiding the glo#al identifier )your friends aretaling a#out you, not the president+