Functions - PowerPoint PPT Presentation

1 / 31
About This Presentation
Title:

Functions

Description:

A good rule of thumb is that a function should not exceed one screen in length ... Impossible: function A calls B, and B calls A ... – PowerPoint PPT presentation

Number of Views:488
Avg rating:3.0/5.0
Slides: 32
Provided by: CMP97
Category:
Tags: bb | functions

less

Transcript and Presenter's Notes

Title: Functions


1
Functions
2
Considering Function Basics
  • A good rule of thumb is that a function should
    not exceed one screen in length
  • if longer you probably doing too much in that
    function
  • break into two or more function
  • Naming and writing functions
  • Every function has a name following the same
    rules that you apply to naming variables
  • All function names have one set of parenthesis
    following them. This helps you (and C)
    differentiate them from variables
  • The body of each function, starting immediately
    after the closing parenthesis of the function
    name, is enclosed in braces containing one or
    more statement

3
A New Example Problem
  • / Find area of circle with radius r /
  • double area (double r)
  • return 3.14 r r
  • New features
  • 1. The return statement sends the value back.
  • 2. The type of the returned value is stated
    before the function name.
  • Specification Write a function which, given the
    radius, computes and returns the area of a circle
    with that radius
  • The new wrinkle here is that the function must
    return a value
  • Returned Values
  • Parameters are a way for the calling routine to
    send data to the function
  • The new concept, return values, are the opposite,
    a way for the function to send data back to the
    calling routine

4
Void Parameters, Non-void Returns
  • This function gives back a number that it
    generates internally, without the need for a
    parameter from the caller
  • / return a random number. /
  • double GenRandom (void)
  • double result
  • result ...
  • return result

function type (type of returned value). We say
GenRandom( ) is a function of type double or
GenRandom( ) returns a double.
local variable exists only while function is
executing
return statement AND value
5
return statement
  • A value-returning function can be used anywhere
    an expression of the same type can be used
  • int main (void)
  • double firstRandom, secondRandom
  • double result
  • firstRandom GenRandom( )
  • secondRandom GenRandom( )
  • result firstRandom secondRandom
  • printf(the value of f f is f.,
    firstRandom, secondRandom,result)
  • return 0
  • For void functionsreturn causes control flow
    to return to the statement following the call in
    the caller.
  • For functions that return a valuereturn
    expression causes control flow to return to the
    caller. The function call is replaced with the
    returned value.
  • Note no parentheses are needed on the expression
  • return is a C statement. It is not a function.

6
return in void Functions
  • Terminate function execution before reaching the
    end (required)
  • / do something /
  • void example (void)
  • int no_reason_to_continue
  • ...
  • if (no_reason_to_continue)
  • return
  • ...
  • Return here is optional
  • / print banner line /
  • void print_banner (void)
  • printf(\n)
  • printf(\n)
  • return

7
Discussion Questions
  • 1. Can you have more than one return inside a
    function?
  • 2. Does a return statement have to be the last
    statement of a function?
  • 3. If a function starts off as
  • double calculation (void)
  • could it contain this statement?
  • return
  • 4. If a function starts off as
  • void printfBankBalance (void)
  • could it contain this statement?
  • return currentBalance

8
Matching up the Arguments
  • Rule The function call must include a matching
    argument for each parameter.When the function is
    executed, the value of the argument becomes the
    initial value of the parameter.
  • int main (void)
  • ...
  • z 98.76
  • x 34.575
  • area ( z/2.0 )
  • return 0

/ Find area of circle with radius r / double
area (double r) return 3.14 r
r Parameter passing
9
Parameters
  • Many people use the term formal parameter instead
    of parameter and actual parameter instead of
    argument. We will try to stick to parameter and
    argument for simplicity, but the other
    terminology will probably slip in from time to
    time.
  • People often refer to replacing a parameter with
    the argument in a function call as passing the
    argument to the function.

10
Review Function Control Flow
  • Some time ago we described the basic flow.
  • We can now give a much more detailed account of
    how this flow works
  • When a function is called
  • Memory space is allocated for the functions
    parameters and local variables
  • Argument values are copied
  • Control transfers to the function body
  • The function executes
  • Control and return value return to the point of
    call.

11
Control and Data Flow
  • / Find area of circle with radius r /
  • double area (double n)
  • return 3.14 n n
  • int main (void)
  • double x, y, z
  • y 6.0
  • x area(y/3.0)
  • ....
  • ....
  • z 3.4 area(7.88)
  • ....
  • return 0

Style Points The comment above a function must
give a complete specification of what the
function does, including the significance of
all parameters and any returned value. Someone
wishing to use the function should be able to
cover the function body and find everything they
need to know in the function heading and
comment.
12
Multiple Parameters
  • A function may have more than one parameter
  • Arguments must match parameters in number, order,
    and type

double gpt, gpa gpt 3.0 3.3 3.9 gpa avg
( gpt, 3 ) ...
parameters
double avg (double total, int count) return
total / (double) count
arguments
13
Rules for Returns
  • What do we know now?
  • We have seen all of the basic concepts for how a
    function communicates with the outside world,
    through parameters and return values
  • We know the syntax involved, as well as the
    logical concepts
  • There is still a topic centered with the internal
    programming of the function the use of local
    variables
  • A function can only return one value --but it
    might contain more than one return statement
  • In a function with return type T, the returned
    expression must be of type T.
  • A function with return type T can be used
    anywhere an expression of type T can be used.

14
Order for Functions in the .c File
  • Function names are identifiers, so they too must
    be declared before they are used
  • include ltstdio.hgt
  • void fun2(void) ...
  • void fun1(void) ... fun2() ...
  • int main(void) ... fun1() ... return 0
  • fun1 calls fun2, so fun2 is defined before fun1,
    etc.
  • Insisting that all the code of each function
    precede all calls to that function is sometimes
  • Impossible function A calls B, and B calls A
  • Inconvenient printf() is a function, but we
    dont want its code in our program
  • But the ordering rule requires that the function
    names be declared before they can be used (in a
    call).
  • Is there any solution?
  • Function Prototypes

15
Solution Function Prototypes
  • Function prototypes allow us to define the name,
    so that it can be used, without giving the code
    for the function.
  • The prototype gives the function name, return
    type, and the types of all the parameters but no
    code.
  • In place of the code block, there is a
    semicolon.
  • Example
  • void Useless(void)
  • void PrintInteger(int value)
  • double CalculateTax (double amount, double
    rate)

16
Using Prototypes
  • Write prototypes for your functions near the top
    of the program
  • Can use the function anywhere thereafter
  • Fully define the function later, wherever
    convenient
  • Highly recommended to aid program organization

17
Function definition format
  • return-type function-name( parameter-list )
    declarations and statements
  • Function-name any valid identifier
  • Return-value-type data type of the result
    (default int)
  • void indicates that the function returns
    nothing
  • Parameter-list comma separated list, declares
    parameters
  • A type must be listed explicitly for each
    parameter unless, the parameter is of type int
  • Definitions and statements function body (block)
  • Variables can be defined inside blocks (can be
    nested)
  • Functions can not be defined inside other
    functions
  • Returning control
  • If nothing returned
  • return
  • or, until reaches right brace
  • If something returned
  • return expression

18
Example
  • 1 / Program UserFunc.c - Creating and
    using a programmer-defined function. /
  • 2
  • 3 include ltstdio.hgt
  • 4
  • 5 int square( int ) / function prototype
    /
  • 6
  • 7 int main()
  • 8 / loop 10 times and calculate and output /
  • 9 for ( int x 1 x lt 10 x )/ square of x
    each time /
  • 10 printf (d , square( x ) ) / function
    call /
  • 11 printf (\n)
  • 12 return 0 / indicates successful
    termination /
  • 13 / end main /
  • 14
  • 15 // square function definition returns square
    of an integer
  • 16 int square( int y ) // y is a copy of
    argument to function
  • 17
  • 18 return y y // returns square of y as an
    int
  • 19 // end function square

19
Local Variables
  • A function can define its own local variables
    (Parameters are also local variables)
  • The locals have meaning only within the function.
  • Local variables are created when the function is
    called.
  • Local variables cease to exist when the function
    returns.

/ Compute area of circle with radius r /
double CircleArea (double r) double x,
area1 x r r area1 3.14 x
return area1
parameter
local variables
20
Global Variables
  • C lets you define variables that are not inside
    any function.
  • Called "global variables."
  • Global variables have legitimate uses, but for
    beginners, they often are
  • a crutch to avoid using parameters
  • poor style
  • General warning!
  • In this course, global variables are completely
    verboten! Only local variables are allowed in
    (homework) programs
  • Note define symbols are global, but
    technically, they are not variables
  • Their use is encouraged!

21
Local Variables Summary
  • (Formal) parameters and variables declared in a
    function are local to it
  • cannot be accessed (used) by other functions
    except by being passed as actual parameters or
    return values)
  • Allocated (created) on function entry,
    de-allocated (destroyed) on function return.
  • (Formal) parameters initialized by copying value
    of argument (actual parameter).
    (Call-by-value)
  • A good idea? YES!
  • localize information reduce interactions.

22
Structuring Program Files
  • The function is the basic unit of a C program
  • Programs often use many functions
  • Some are defined within the program
  • Some are in libraries
  • Organizing and ordering the functions and other
    parts within the .c file is important
  • Order in the program
  • General principle identifiers (names of things)
    must be declared before they are used.
  • Variables
  • place them first within each function
  • define constants placed at the top of the .c
    file
  • define CONST value
  • Functions
  • Use prototypes!

23
Library Functions
  • What about library functions, like printf?
  • You must also tell the compiler that you are
    going to use the library which contains printf
  • This is the purpose of the include directive
  • The linker knows where the libraries are
  • include ltstdio.hgt
  • The include means go get the file stdio.h and
    insert whats in it right here (as if it had been
    typed here)
  • stdio.h contains function prototypes for scanf
    and printf and the other functions in the
    standard I/O library
  • The actual code for them is NOT there, just
    prototypes. The (result of compiling) the code
    is in a library that is combined with your code
    by the linker

24
Compilers, Linkers, etc.
.c file
011010001101
executable program
COMPILER
LINKER
header (stdio.h)
library (ANSI)
object code
source code
  • All Together
  • include directives
  • define constants
  • Function prototypes
  • Full function definitions

25
Logical Order vs. Control Flow
  • With prototypes, the functions can be placed in
    any physical order
  • Order within the source file has no influence on
    control flow
  • Programs always start at the function main
  • So there should always be a main
  • No function is executed until it is called by
    some other function
  • Only exception main
  • To summarise
  • Organizing the parts of a .c file is important
  • General principle identifiers must be declared
    before they are used
  • For functions, a prototype can be declared near
    the beginning of the program
  • Function can be defined in detail later
  • For libraries, mention the library name in a
    include directive
  • Source order and control flow are different
    concepts

26
Testing Comprehension
  • What is the function prototype for
  • main()
  • double x, y, w
  • w funct1(x, y)
  • double funct1(double a, double b)
  • double c
  • c .
  • return(c)
  • What do these mean?
  • double f(double a, int b)
  • Function prototype - f accepts 2 arguments and
    returns double precision quantity
  • void f(int a)
  • Function accepts integer and returns nothing
  • What is the first line in the function definition
    of
  • A function called root, it accepts two integer
    arguments and returns a float
  • float root(int a, int b)

double funct1(double a, double b)
27
Testing Comprehension
  • function to find Volume of Cylinder
  • include ltstudio.hgt
  • include ltmath.hgt
  • define PI 3.141592654
  • main()
  • double volume, height, radius, result
  • printf(Enter radius of Cylinder)
  • scanf(lf, radius)
  • printf(Enter Height of Cylinder)
  • scanf(lf, height)
  • result base(radius)
  • volume height result
  • printf(Base Area lf\n Volume islf\n,
    result, volume)
  • //END MAIN
  • /function definition/
  • double base( double r)
  • // parameter declaration
  • double area
  • // variable declaration
  • area PI pow(r,2)
  • printf(Radius squared lf\n Area lf\n ,
    pow(r,2), area)
  • return(area)

28
Storage Classes
  • Identifiers have
  • name
  • type
  • size
  • value
  • Other attributes
  • storage class
  • storage duration (period during which variable
    exist in memory)
  • scope (portion of the program where the variable
    can be seen)
  • linkage (for multiple source file, which files
    can use it)

Storage Class specifiers auto auto double x,
y register register int counter
1 static static int count 1 extern extern
int flag these determine duration scope
linkage
29
Storage Duration
  • the 4 storage classes can be split into 2 storage
    durations
  • automatic storage duration
  • keywords auto and register
  • static storage duration
  • keywords extern and static)

automatic storage duration created on
entry destroyed upon exit e.g. a functions
local variable only variables! principle of least
privilege
static storage duration storage is
allocated and variable is initialised ONLY once
(when program starts execution) exist until
program terminates e.g. global variables,
function names
30
Scope rules
  • function scope
  • local variables, labels in switch statement
  • file scope
  • declared outside any function
  • seen everywhere!
  • block scope
  • declared inside block starts with ends with
  • seen only inside that block
  • function prototype scope
  • variables in parameter list of function prototype

31
Linkage
  • whether a name is known only in the current
    source file, or in other source files with the
    proper declaration

program
source_file_2.c extern int flag // variable
declarations
source_file_1.c int flag // global variable
Write a Comment
User Comments (0)
About PowerShow.com