ProgrammerDefined Functions - PowerPoint PPT Presentation

1 / 34
About This Presentation
Title:

ProgrammerDefined Functions

Description:

'Variable name' used to refer to data in definition of function ... Scope of Names. Region of a program where meaning of name is visible or can be referenced ... – PowerPoint PPT presentation

Number of Views:70
Avg rating:3.0/5.0
Slides: 35
Provided by: kal7
Category:

less

Transcript and Presenter's Notes

Title: ProgrammerDefined Functions


1
Chapter 5
  • Programmer-Defined Functions

2
Programmer-Defined Functions
  • Building blocks of programs
  • A program that is more than 25 lines long should
    be broken up into functions that have no more
    than 25 lines.
  • The divide-and-conquer approach makes program
    development more manageable

3
Advantages of Functions
  • Facilitates top down design
  • Facilitates bottom up implementation and testing
  • Each function can be implemented and tested
    separately.
  • Facilitates software reuse
  • with good function naming and definition,
    programs can be created from standardized
    functions that accomplish specific tasks.

4
Advantages of Functions
  • Avoids repetition of code in a program
  • can invoke a function from different locations in
    a program
  • Improves readability

5
Functions
  • From the Linux kernel Coding Style Guide Chapter
    5 Functions
  • Functions should be short and sweet, and do just
    one thing. They should fit on one or two
    screenfuls of text (the ISO/ANSI screen size is
    80x24, as we all know), and do one thing and do
    that well.

6
Functions
  • The maximum length of a function is inversely
    proportional to the complexity and indentation
    level of that function. So, if you have a
    conceptually simple function that is just one
    long (but simple) case-statement, where you have
    to do lots of small things for a lot of different
    cases, it's OK to have a longer function.
  • However, if you have a complex function, and
    you suspect that a less-than-gifted
    first-year-high-school student might not even
    understand what the function is all about, you
    should adhere to the maximum limits all the more
    closely. Use helper functions with descriptive
    names (you can ask the compiler to inline them if
    you think it's performance-critical, and it will
    probably do a better job of it than you would
    have done).

7
Functions
  • Another measure of the function is the number of
    local variables. They shouldn't exceed 5-10, or
    you're doing something wrong. Re-think the
    function, and split it into smaller pieces. A
    human brain can generally easily keep track of
    about 7 different things, anything more and it
    gets confused. You know you're brilliant, but
    maybe you'd like to understand what you did 2
    weeks from now.

8
Functions
  • A function cannot be executed by itself must be
    called into execution by a main program or
    another subprogram

9
Programmer-Defined Functions
  • Definition can go in either
  • Same file as main()
  • Separate file so others can use it, too
  • In this course, functions will generally go in
    the same file as main().
  • In CpSc 102, functions will probably go in
    separate files.

10
Components of Function Use
  • 3 Pieces to using functions
  • Function declaration/prototype
  • Function definition
  • Function call

11
Function declaration/protoytpe
  • An informational declaration for compiler
  • Tells compiler how to interpret calls
  • Consists of
  • return type
  • name of the function
  • parenthesized declaration of function parameters

12
Function declaration/prototype
  • Placed before any calls
  • In declaration space of main()
  • Or above main() in global space
  • We will generally place function prototypes above
    main() in global space.
  • Syntax fnName(t)
  • Example
  • void printStars()

13
Function Definition
  • A C function definition is comprised of 4
    components
  • the return type
  • the name of the function
  • parenthesized declaration of function parameters
  • at least one basic block containing local
    variable declarations and executable code
  • main is a function
  • int main (int argc, char argv )
  • //basic block

14
Function Definition Placement
  • Placed after/before function main()
  • NOT 'inside' function main()!
  • Functions are 'equals' no function is ever
    'part' of another

15
Example Function Definition
  • /
  • This function prints 25 s and then a newline
  • /
  • void printStars( )
  • int count 0
  • while (count
  • fprintf(stdout, )
  • count count 1
  • fprintf(stdout, \n) // must be
    outside the loop

16
Example Function Call
  • To use the function, assuming it is defined after
    main()
  • include
  • void printStars( ) // function prototype
  • int main( )
  • printStars() // function call
  • printStars() // function call
  • return 0
  • Execution will produce

17
Example Function Call
  • The preceeding function is somewhat restrictive.
  • What if we want to print more/less s?
  • We can tell the function how many to print.
  • We will do this by declaring a parameter to
    receive this information. e.g.
  • void printStars(int howmany)

18
Example Function Definition
  • /
  • This function prints n s and then a newline,
    where
  • n is passed to the function
  • /
  • void printStars( int n)
  • int count 0
  • while (count
  • fprintf(stdout, )
  • count count 1
  • fprintf(stdout, \n) // must be
    outside the loop

19
Example Function Call
  • Now, what if we want to print a symbol other than
    a ?
  • We can define a general function that can print
    any symbol.
  • Instead of passing just the number of symbols to
    print per line, we will also pass the symbol to
    be printed. e.g.
  • void printSymbol(char symbol, int howmany)

20
Example Function Definition
  • /
  • This function prints a row of n symbols and
    then a newline,
  • where symbol and n are passed to the function
  • /
  • void printSymbol(char symbol, int n)
  • int count 0
  • while (count
  • fprintf(stdout, c, symbol)
  • count count 1
  • fprintf(stdout, \n) // must be
    outside the loop

21
Function Call
  • Transfers control to the function
  • For value-returning functions, either
  • Use the value returned, as in
  • fprintf(stdout, .2lf\n, totalCost(number,
    price)
  • or store the value for later use.
  • bill totalCost(number, price)

22
Parameters (Arguments)
  • Formal parameters/arguments
  • In function declaration
  • In function definition's header
  • 'Placeholders' for data sent in
  • 'Variable name' used to refer to data in
    definition of function
  • Actual parameters/arguments
  • In function call

23
Parameter vs. Argument
  • Names used interchangeably
  • Technically, parameter is 'formal' piece (in
    prototype, header), while argument is 'actual'
    piece (in function call)

24
Functions Calling Functions
  • We're already doing this!
  • main() IS a function!
  • Only requirement
  • Function's declaration must appear before the
    function is called.

25
Functions Calling Functions
  • Common for functions to call many other functions
  • Function can even call itself ? 'Recursion
  • You will study recursion in a later course.

26
Calling Void Functions
  • Same as calling predefined void functions
  • From some other function, like main()
  • showResults(degreesF, degreesC)
  • showResults(32.5, 0.3)
  • Cannot be used where a value is required.
  • Cannot be assigned to a variable, since no value
    returned

27
Return Statements
  • Transfers control back to 'calling' function
  • For return type other than void, definition MUST
    have return statement
  • Typically the LAST statement in function
    definition

28
Example of Value-Returning Function
  • Example
  • // precondition n 0
  • int factorial ( int n) int result 1
  • while ( n 0)
  • result result n
  • n n 1
  • return result

29
main() Special
  • Recall main() IS a function
  • 'Special' in that
  • One and only one function called main() will
    exist in a program

30
main() Special
  • Who calls main()?
  • Operating system
  • Tradition holds it should have return statement
  • Value returned to 'caller' ? Here operating
    system
  • Should return 'int'

31
Scope of Names
  • Region of a program where meaning of name is
    visible or can be referenced
  • Local variables
  • Declared inside body of given function
  • Available only within that function
  • Can have variables with same namesdeclared in
    different functions

32
Scope Rules
  • Local variables preferred
  • Maintain individual control over data
  • Need to know basis
  • Functions should declare whatever local data
    needed to 'do their job'

33
Global Constants and Global Variables
  • Declared 'outside' function body
  • Global to all functions in that file
  • Global declarations typical for constants
  • const double TAXRATE 0.05
  • Declare globally so all functions have scope

34
Global Constants and Global Variables
  • Global variables?
  • Possible, but SELDOM-USED
  • Dangerous no control over usage!
Write a Comment
User Comments (0)
About PowerShow.com