Functions in C - PowerPoint PPT Presentation

1 / 40
About This Presentation
Title:

Functions in C

Description:

A prototype looks like a heading but must end with a semicolon. ... called function followed by()s that enclose an argument list, which may be empty ... – PowerPoint PPT presentation

Number of Views:41
Avg rating:3.0/5.0
Slides: 41
Provided by: keen85
Category:

less

Transcript and Presenter's Notes

Title: Functions in C


1
Functions in C
  • Top Down Design with Functions

2
Top-down Design
  • Big picture first
  • broken down into smaller pieces

3
Can you tell what this is doing?
  • int main ()
  • rad get_a_number()
  • display_input (rad)
  • pie_area find_area (rad)
  • pie_cost calccost (pie_area)
  • draw_pie (rad, pie_cost)
  • return 0

4
Why use functions?
  • easier for programmers to work together
  • put details off while looking at big picture
  • easier to reuse code
  • easier testing and debugging

5
Function Syntax
  • Prototypes
  • before function call
  • usually after using namespace std
  • Calls
  • value returning
  • void
  • Definitions
  • placement optional

6
Two Parts of Function Definition
  • int Cube(int n) heading
  • body
  • return n n n

7
What is in a heading?
type of value returned
parameter list
name of function
int Cube (int n)
8
Prototypes
A prototype looks like a heading but must end
with a semicolon. Its parameter list should
contain the types and names of each parameter
the names are optional but good to have! int
Cube(int value ) // Prototype
9
Arguments / Parameters
  • They are the interface between the function and
    the "outside world"
  • have number, names, types
  • Their number and types must match
  • matching is done by position - first to first,
    second to second, etc.
  • careful about using "input" and "output" in
    referring to parameters - NOT from the keyboard
    and to the screen!

10
Functions
  • Every C program must have a function called
    main
  • Program execution always begins with function
    main
  • Any other functions are subprograms that must be
    explicitly called

11
Function Calls
  • One function calls another by using the name of
    the called function followed by()s that enclose
    an argument list, which may be empty
  • A function call temporarily transfers control
    from the calling function to the called function

12
Function Semantics
  • When a function is called
  • Arguments and parameters matched (if any)
  • Local variables and constants created
  • space for return value allocated if not void
  • Function code executed
  • Return statement or end of code inside brace
    causes locals to be destroyed and control to
    return to calling statement
  • If a value is to be returned, it is sent back

13
Functions with no return value
  • Syntax
  • void return type
  • can use return statement or no return statement
    at all
  • Semantics of execution
  • called in a statement by itself
  • executes function code with arguments
  • returns to next statement after call

14
Functions with a return value
  • Syntax
  • return type of some builtin type
  • must use return x statement where x is some
    value or variable of the given return type
  • Semantics of execution
  • called as part of larger statement
  • executes function code with arguments
  • returns a value to the calling statement

15
  • include ltiostreamgt
  • int Cube(int) // prototype
  • using namespace std
  • void main()
  • int yourNumber
  • int myNumber
  • yourNumber 14
  • myNumber 9
  • cout ltlt My Number ltlt myNumber
  • cout ltlt its cube is ltlt Cube(myNumber) ltlt
    endl
  • cout ltlt Your Number ltlt yourNumber
  • cout ltlt its cube is ltlt Cube(yourNumber)
  • ltlt endl
  • arguments

16
Return Values
  • In C, a value-returning function returns one
    value of the type specified in its heading and
    prototype (called the return type)
  • In contrast, a void-function does not return any
    value

17
Example
  • Write a void function called DisplayMessage(),
    which you can call from main(), to describe the
    pollution index value it receives as a parameter
  • Your city describes a pollution index
  • less than 35 as Pleasant,
  • 35 through 60 as Unpleasant,
  • and above 60 as Health Hazard

18
  • parameter
  • void DisplayMessage(int index)
  • if(index lt 35)
  • cout ltlt Pleasant
  • else if(index lt 60)
  • cout ltlt Unpleasant
  • else
  • cout ltlt Health Hazard

19
The Rest of the Program
  • include ltiostreamgt
  • void DisplayMessage(int polIndex) // Prototype
  • using namespace std
  • int main()
  • int pollutionIndex
  • cout ltlt Enter air pollution index
  • cin gtgt pollutionIndex
  • DisplayMessage( pollutionIndex ) // Call
  • return 0
  • argument

19
20
Return Statement
  • return // No value to return
  • Is valid only in the body block of a void
    function
  • Causes control to leave the function and
    immediately return to the calling block, leaving
    any subsequent statements in the function body
    unexecuted

21
Value-Returning Functions
  • include ltiostreamgt
  • int Square(int) // Prototypes
  • int Cube(int)
  • using namespace std
  • int main()
  • cout ltlt The square of 27 is
  • ltlt Square(27) ltlt endl
  • cout ltlt The cube of 27 is
  • ltlt Cube(27) ltlt endl
  • return 0
  • function calls

21
22
Rest of Program
  • int Square(int n) // Header and body
  • return n n
  • int Cube(int n) // Header and body
  • return n n n

23
Parameter List
  • A parameter list is the means used for a function
    to share information with the block containing
    the call to the function.

24
Classified by Location
  • Arguments Parameters

Always appear in a function call within the
calling block
Always appear in the function heading, or
function prototype
25
Scope
  • "Where is this identifier known?"
  • Parameters
  • from header line of function to right closing
    brace
  • Local variables
  • from line of declaration inside function
    definition to right closing brace
  • Global variables
  • from line of declaration to end of FILE -
    includes all functions following the declaration

26
Scope continued
  • Local variables
  • created every time the function runs
  • initializations done every time they are created
  • destroyed when the function returns control

27
Scope continued
  • Parameters
  • name is known from header line until end of
    function body
  • NAME does NOT have to match argument NAME
  • if passed by value, gets memory allocated and
    copy of argument made
  • if passed by reference, gets matched with space
    occupied by argument

28
Scope continued
  • Global variables
  • declared outside of any function at all
  • known from that point in file to end of FILE
  • allocated space at start of execution of main
  • destroyed when main function returns control
  • may be "shadowed" by local variables with same
    name, so the global can't be accessed

29
Scope continued
  • Why are global variables BAD?
  • cause "side effects" - allow a function to do
    something "behind your back"
  • what a function can affect / change should always
    be documented in its header
  • make it harder to reuse code - can't just pick up
    the code and copy it to another program
  • make it harder for people to work on teams

30
"Everything global"
  • Do NOT be tempted to "make everything global" -
    it is a sure way to introduce bugs!!!!
  • If a function header were "void PrintLine (int
    datavalue)" you would NOT expect it to change a
    variable called "totaldata", would you?

31
Interface Design
  • parameters are either "in", "out" or "in/out"
  • value if data just coming IN to function
  • reference or the return value if going OUT
  • reference if coming IN and going back OUT

32
A Parameter or a Local Variable
  • How to decide
  • ask yourself "does this information need to COME
    FROM some other function?" parameter
  • "does this information need to GO TO some other
    function?" parameter or return value
  • "does ONLY this function need to know about this
    data?" local

33
Stubs and Drivers
  • "Scaffolding"
  • Stubs - top-down
  • Drivers - bottom-up

34
A Driver Program
  • A driver program is a short main program whose
    only purpose is to test another program
  • Write a driver for function GetRating()

35
Questions
  • Why is a function used for a task?
  • To cut down on the amount of detail in your main
    program (encapsulation)
  • Can one function call another function?
  • Yes
  • Can a function even call itself?
  • Yes, that is called recursion it is very
    useful and requires special care in writing

36
More Questions
  • Does it make any difference what names you use
    for parameters?
  • No just use them in function body
  • Do parameter names and argument names have to be
    the same?
  • No

37
An Assertion
  • An assertion is a truth-valued statement--one
    that is either true or false (not necessarily in
    C code)
  • Examples
  • studentCount gt 0
  • sum is assigned count gt 0
  • response y or n
  • 0.0 lt deptSales lt 25000.0
  • beta beta _at_ entry 2

38
Preconditions and Postconditions
  • A precondition is an assertion describing
    everything that the function requires to be true
    at the moment the function is invoked
  • A postcondition describes the state at the moment
    the function finishes executing, providing the
    precondition is true
  • The caller is responsible for ensuring the
    precondition, and the function code must ensure
    the postcondition

For example . . .
39
Function with Postconditions
  • char GetRating( char letter)
  • // Precondition None
  • // Postcondition User has been prompted to enter
    a letter
  • // letter one of these input values
    E,G,A, or P
  • cout ltlt Enter employee rating. ltlt endl
  • cout ltlt Use E, G, A, or P
  • cin gtgt letter
  • while((letter ! E) (letter ! G)
    (letter ! A) (letter ! P))
  • cout ltlt Rating invalid. Enter again
  • cin gtgt letter
  • return letter

39
40
Documentation of Function
  • Short comment at prototype
  • Header comment longer
  • purpose of function, using the names of all
    parameters and the return value if any
  • comment code in body as usual
  • pre and post conditions
  • Sometimes put comment at closing brace that just
    has function name in it, makes it easier to match
    braces for the body
Write a Comment
User Comments (0)
About PowerShow.com