Functions - PowerPoint PPT Presentation

1 / 25
About This Presentation
Title:

Functions

Description:

A function may require values to perform its task. ... not too many lines in one 'hunk' functional division. division of labor. reusability ... – PowerPoint PPT presentation

Number of Views:87
Avg rating:3.0/5.0
Slides: 26
Provided by: donaldl1
Category:
Tags: functions | hunk

less

Transcript and Presenter's Notes

Title: Functions


1
Functions
  • Part 1

2
Outline of Topics
  • What is a function
  • Benefits of using functions
  • Terminology related to functions
  • Library functions
  • Using functions
  • Writing functions

3
What is a Function?
  • a module or routine which is invoked (i.e.,
    "called") to perform a specified task. A
    function may require values to perform its task.
    These are made available to the function as
    parameters (i.e., arguments). The function may
    return a value. The number and nature of the
    arguments and returned value, if any, are
    specified when the function is written.

4
What goes into a function?
  • a function should perform a single, well-defined
    task
  • a function should be given a name which is
    descriptive of the task
  • a function should adhere to the principle of
    "least privilege"
  • a function should not be given access to any data
    beyond what is required for it to do its work
  • a function should not be given privileges with
    respect to the data that it does not need (e.g.,
    a function that needs to read a particular value,
    but does not need to change it, should be
    prevented from making such a change)
  • the function or class provider should provide the
    API or documentation describing how to access and
    use the function

5
Why Use and Create Functions?
  • Modularizes programs
  • readability manageability
  • not too many lines in one "hunk"
  • functional division
  • division of labor
  • reusability
  • code for one function only written once
  • Keeps all related info (i.e., data) together
  • Access to prewritten routines
  • reduces cost
  • improves reliability
  • increases consistency
  • improves performance

6
Example of a Simple Function
  • prototype
  • void printResult(double) //note the structure
    and the punctuation
  • invoking the function
  • int main(void)
  • printResult(amt) //the value stored in amt is
    copied, and passed to the ftn
  • ...
  • defining the function
  • void printResult(double finalTotal) //finalTotal
    is the name used within the ftn
  • coutltlt "\n\nSales Total " ltlt setw(10) ltlt
    setprecision(2)
  • ltlt setiosflags(iosfixed) ltlt finalTotal ltlt
    endl

7
Terminology Related to Functions
  • declared declaration
  • defined definition
  • invoked called
  • signature
  • function call
  • library function
  • standard library

8
Terminology Related to Functions (more)
  • arguments
  • parameters
  • actual parameters
  • formal parameters
  • call by value
  • reference parameters
  • overloaded functions

9
Math functions
  • need library "math.h" or "cmath"
  • absolute value -- fabs(-12.3)
  • "rounding off" -- floor(7.3)
  • raised to a power, 154.8 squared -- pow(154.8, 2)
  • square root -- sqrt(36.2)

10
Calling statement
  • static functions (i.e., class methods)
  • CTimegetCurrentTime()
  • MyClassmyStaticMethod()
  • member functions (instance/object method) can
    only be accessed by objects of that class
  • bankAcct.setBalance(1500.)
  • calcAmt() //error no object reference
  • others
  • turnLeft(45)
  • floor(currentBalance) //library function

11
Function Definition
  • Definition describes
  • the function's interface
  • what the function requires when called
  • what the function returns when execution is
    complete
  • the function's logic
  • Example
  • double takeDeprec(int numAccidents, double
    blueBook, Car aCar)

12
Function Definition
  • A function is similar to a separate program
  • It can use (i.e., knows) only
  • passed parameters
  • local variables
  • globals (externals)
  • Function can include any type of logic, I/O, file
    operation, loop or other statement
  • A function can only return one value (!)

13
Parameter Passing
  • Normally parameters passed "by value"
  • A copy of each parameter is made when the
    function is called
  • Temporary copies are used by the function
  • Temporary copies are discarded when the function
    completes execution

14
Declaration (or Prototype)
  • Included in program prior to reference or use of
    a particular function
  • could be within a function, such as main
  • could be of file scope
  • May be contained in an "included" header file
  • Specifies
  • return type
  • function name
  • number, order, and type of arguments
  • Prototypes are not actually required by Cif the
    definition precedes use (but our convention is to
    use prototypes)

15
Examples of Prototypes
  • double calcAmt(double, string, int)
  • void printValues(Customer, int)
  • Can include variable names, but they are ignored.
    So the above would be
  • void printValues(Customer myCust, int count)
  • double calcAmt(SalesTrans )
  • looks stranger than
  • double calcAmt(SalesTrans salesArray25)

16
Purpose of prototype, definition and calling stmt
  • prototype specifies the type of value
    returned, and the number, type and order of
    arguments for the function. The prototype allows
    the compiler to verify that the use (i.e.,
    invokations) of the function are correct with
    respect to the number, type, and order of
    parameters, and the returned value
  • definition specifies the info provided by the
    prototype, as well as the names of the variables
    that have been passed as arguments (i.e., the
    "formal parameters"). The curly braces contain
    the logic
  • calling statement sends the actual values
    (i.e., the "actual parameters") to the function,
    which carries out the specified operations (i.e.,
    the logic), and accepts the value which is
    returned by the function

17
Relationship of calling stmt, prototype and
definition
  • Prototype double findRate(Car, int)
  • Definition double findRate(Car aCar, int
    numDays)
  • Calling Stmt amtDue findRate(theCar, 12)disc
  • Usually appear in the order
  • prototype (with file scope, but could be within a
    function, or in a header file)
  • calling statement (within main or another
    function called from main)
  • definition (after main, or perhaps in another
    file never within another function)

18
inline functions
  • use the keyword inline prior to the return type
    in the function definition
  • duplicates the code and inserts it everywhere it
    is invoked
  • example
  • inline double calcValue(const double amt)
  • .

19
Default arguments
  • prototype
  • double myFunct(int val125, double val2 34.8)
  • call
  • double amt myFunct (87)
  • definition
  • is normal

20
Using an Array as a Parameter
  • PROTOTYPES
  • int totalTheArray(int )
  • IN MAIN
  • DECLARATIONS
  • int salesArray10
  • INVOKING THE FUNCTION
  • total totalTheArray(salesArray)
  • FUNCTION DEFINITION
  • int totalTheArray(int theArray)

21
Call by Reference
  • avoids memory and time cost of duplicating the
    actual parameters -- no copy of reference arg is
    made!!!
  • prototype
  • void myFunction (double )
  • invokation
  • returnedValue myFunction(inputAmt)
  • definition
  • void myFunction (double workingValue)
  • // can change the value of workingValue
  • // no return of a value

22
Example of Reference Args
  • //PROTOTYPES
  • void addUmUp(int , int , int )
  • int main(void)
  • ...
  • //CALL OF THE FUNCTION
  • addUmUp(i, j, k)
  • //FUNCTION DEFINITIONS
  • void addUmUp(int firstVal, int secondVal, int
    thirdVal)
  • firstVal secondVal thirdVal

23
Importance of Prototypes and Having a Unique
Signature
  • //CONSIDER THE FOLLOWING PROTOTYPES
  • void addUmUp(int , int , int )
  • //void addUmUp(int, int, int) //Note if this
    were included
  • //then call addUmUp(i, j, k) will be
    ambiguous since
  • //the compiler does not determine call by
    reference or
  • //call by value
  • //int addUmUp(int, int, int) //Note if this
    were included
  • //then this creates an ambiguous
    reference since
  • //it differs only by return type
  • with calling statement addUmUp(i, j, k)

24
Summary of Functions
  • Well written programs utilize ftns extensively
  • Functions should perform a single purpose (but
    this can be a "compound" purpose)
  • Choose a ftn name descriptive of the purpose
  • Choosing what goes into a function can be
    difficult (use guidelines, experience and
    experimentation)

25
Summary of Functions (more)
  • Functions are in many respects like separate
    programs
  • To understand how a function works you need to
    understand
  • flow of control
  • upon invokation, execution of the function starts
  • upon ending of the function, the calling module
    resume execution
  • transfer of information
  • Understand call by value
  • Reference parameters
  • Pointers (covered later in the course)
Write a Comment
User Comments (0)
About PowerShow.com