Functions - PowerPoint PPT Presentation

1 / 76
About This Presentation
Title:

Functions

Description:

cin a b; max = FindMax(a,b); cout 'The max of the two is ' max; ... The max of the two is 7. CS 1284 Introduction to Computer Programming. Assignment ... – PowerPoint PPT presentation

Number of Views:24
Avg rating:3.0/5.0
Slides: 77
Provided by: bridges
Category:
Tags: functions

less

Transcript and Presenter's Notes

Title: Functions


1
Functions
  • Reading Chapter 6

2
Functions
  • A C program is a collection of one or more
    subprograms known as functions
  • There must be a function named main()
  • The operating system calls it, the programmer can
    not call it
  • Program execution always begins with the first
    statement in function main()
  • Any other functions in the program must be called
    by the programmer
  • They are not executed until they are called

3
Why use functions?
  • Top-down, modular design easily implemented by
    translating each module into a function
  • Advantages of using functions
  • Readability
  • Debug ability
  • Reusability
  • C depends very heavily on functions
  • Library functions
  • Programmer written functions

4
Function concept in math
  • f ( x ) 5 x - 3

Function definition
Parameter of function
Name of function
  • When x 1, f ( x ) 2 is the returned
    value.
  • When x 4, f ( x ) 17 is the returned
    value.
  • Returned value is determined by the function
    definition and by the values of any parameters.

5
What is a C function?
  • A function is a program module that performs some
    particular task.
  • A function has a name that can be used to
    reference (or call) the function.
  • The function name is preceded by the return type.
  • The function name is followed by the parameter
    list in parentheses (sometimes there will be no
    parameters and so the parentheses will be empty).

6
Function Execution
  • A function call temporarily transfers execution
    from the calling function to the called
    functions code.
  • When the functions code has finished executing,
    control is transferred back to the calling
    function.
  • At that point, execution will return to where it
    left off at the call
  • If the return type is not void, the function
    returns a value to the calling place.

7
Function Definition
  • All the statements in the function
  • Tells C what actions to take in the function
  • Also called the body of the function
  • Must be enclosed inside

void CalculateSquare(void) int number
cout ltlt "Enter a number " cin gtgt number
cout ltlt "Your number squared is " ltlt number
number
8
Function Declaration
  • The function declaration tells C that the
    function can be called later in the program
  • The declaration must appear before the function
    is called
  • Also called the function Prototype and must state
  • The return type
  • The function name
  • The data types of the parameters
  • It need not state the names of the parameters
  • But it is a good idea to include the names

9
Function Declaration
void CalculateSquare(void) void main(void)
cout ltlt "CALCULATING SQUARES\n"
CalculateSquare() cout ltlt "\nWe are
done!\n"
10
Function Call
  • The function call (or invocation) is where the
    function is used.
  • A function is called using the name and an
    argument list.
  • functionName( Argument List )
  • The argument list is a way for functions to
    communicate with each other by passing
    information.
  • The argument list can contain 0 or more
    arguments, separated by commas.

11
Function Call
void CalculateSquare(void) void main(void)
cout ltlt "CALCULATING SQUARES\n"
CalculateSquare() cout ltlt "\nWe are
done!\n"
12
Example of a Function
include ltiostream.hgt void CalculateSquare(void)
void main(void) cout ltlt "CALCULATING
SQUARES\n" CalculateSquare() cout ltlt
"\nWe are done!\n" void CalculateSquare(void)
int number cout ltlt "Enter a number "
cin gtgt number cout ltlt "Your number squared
is " ltlt number number
CALCULATING SQUARES
Enter a number
4
Your number squared is 16
We are done!
13
Return Values
  • A value-returning function always returns a
    single value to its caller and is called from
    within an expression.
  • A return value is substituted for the function
    call when the function is done
  • The return value must have a data type
  • void means no return value
  • A void function never returns a value to its
    caller, and is called as a standalone statement.

void CalculateSquare(void)
14
The return Statement
  • A function executes until
  • the closing brace is reached
  • or a return statement is executed
  • The return statement determines the return value
  • return expression / returning value /
  • return / for return type void /
  • Usually the return statement should be the last
    statement in the function

15
Function Return Example
include ltiostream.hgt int CalculateSquare(void) v
oid main(void) int square cout ltlt
"CALCULATING SQUARES\n" square
CalculateSquare() cout ltlt "Your number
squared is " ltlt square cout ltlt "\nWe are
done!\n" int CalculateSquare(void) int
number cout ltlt "Enter a number " cin gtgt
number return numbernumber
CALCULATING SQUARES Enter a number 4 Your number
squared is 16 We are done!
16
Passing Values
  • Giving a functions values to work with
  • Function calls can pass several values
  • FunctionName(argument, ..., argument)
  • You need to declare parameters for this
  • returnType FunctionName(declaration, ...,
    declaration)
  • There must be a match between the function call
    and the function declaration/definition

17
Arguments Parameters
  • Arguments
  • Always appear in a function call within the
    calling block
  • Also known as actual parameters
  • Parameters
  • Always appear in the function heading, or
    function prototype
  • Also known as formal parameters

18
Example
include ltiostream.hgt int FindMax(int number1,
int number2) void main(void) int a, b,
max cout ltlt "Enter two integers " cin gtgt
a gtgt b max FindMax(a,b) cout ltlt "The
max of the two is " ltlt max int FindMax(int
number1, int number2) if (number1 gt
number2) return number1 else
return number2
Enter two integers 4 9 The max of the two is 9
Enter two integers 7 3 The max of the two is 7
19
Assignment
  • Write a program that will calculate the area of a
    circle
  • Ask the user to enter the diameter (integer type)
    and then validate the diameter (gt 0). This is to
    be done in a function that will also return the
    diameter to main.
  • Pass the diameter to another function that will
    calculate the area and then return the area.
  • Display the area (to be done in main).

20
Local/Global Variables
  • Local (Internal) Variable
  • Any variable declared inside a function/block
  • Local to the function/block where it is declared
  • Can be accessed only inside that function/block
  • Global (External) variable
  • Typically declared outside and before main()
  • Can be accessed anywhere in the program

21
Example
include ltiostreamgt include ltiomanipgt using
namespace std void PrintAveragePay(float
totalPay) int numberOfPeople void main(void)
float totalPay cout ltlt "Enter people and
pay " cin gtgt numberOfPeople gtgt totalPay
PrintAveragePay(totalPay) void
PrintAveragePay(float totalPay) cout ltlt
fixed ltlt setprecision(2) cout ltlt "Average pay
is " ltlt totalPay / numberOfPeople
Global Variable
Local Variable
22
Example
Enter people and pay 5 1501.5 Average pay is
300.30
23
Existing Functions
  • Prototypes for existing functions found in header
    files (they have a .h extension)
  • The definitions for these functions are found in
    libraries of object code
  • Header files also contain definitions of
    constants that may be platform dependent
  • You must include the header file for a library
    in order to use the functions

24
Common library functions
25
Terminating a Program
  • Normal way of terminating is when C runs out of
    statements in the main() function
  • However, you may want the program to stop in
    unusual circumstances
  • Use exit() function (defined in ltcstdlibgt)
  • void exit(int status)
  • Use EXIT_SUCCESS or EXIT_FAILURE to tell C how
    the program is terminating

26
Generating Random Numbers
  • The random number generator supplied by C is a
    pseudo random number generator
  • Include the header file ltcstdlibgt
  • The function rand() generates random integers
    between 0 and RAND_MAX
  • RAND_MAX is a large positive integer constant
    defined in ltcstdlibgt

27
Example
  • include ltiostreamgt
  • include ltcstdlibgt // defines rand()
  • using namespace std
  • void main( )
  • cout ltlt "Five random numbers\n\n"
  • for (int i 1 i lt 5 i)
  • cout ltlt rand() ltlt " "

Five random numbers 41 18467 6334 26500 19169
Five random numbers 41 18467 6334 26500 19169
28
Seeding the Random Number Generator
  • The same sequence will be generated each time
    rand() is invoked unless the random number
    generator is seeded.
  • The function srand() is used to give a starting
    value to the random number generator.
  • It has one argument that is the starting value.
  • The rand() function will return the same sequence
    of random numbers if you seed the srand()
    function with the same value

29
Example
  • include ltiostreamgt
  • include ltcstdlibgt // defines rand() and srand()
  • using namespace std
  • void main( )
  • srand(10)
  • cout ltlt "Five random numbers\n\n"
  • for (int i 1 i lt 5 i)
  • cout ltlt rand() ltlt " "

Five random numbers 71 16899 3272 13694 13697
Five random numbers 71 16899 3272 13694 13697
30
Seeding with different values
  • You can get different sequence of random numbers
    if you seed the srand() function with different
    values
  • The system clock is often used to get a starting
    seed value
  • Use the time() function to seed the srand()
    function with different value every time
  • The time() function returns the number of seconds
    elapsed since midnight (000000), January 1,
    1970
  • Example srand( time(0) )

31
Example
include ltiostreamgt include ltcstdlibgt // defines
rand() and srand() include ltctimegt // defines
time() using namespace std void main( )
srand( time(0) ) cout ltlt "Five random
numbers\n\n" for (int i 1 i lt 5 i)
cout ltlt rand() ltlt " "
Five random numbers 17062 9522 19938 13700 8571
Five random numbers 17353 15859 4218 25415 9065
32
Controlling the Range of Random Numbers
include ltiostreamgt include ltcstdlibgt // defines
rand() and srand() include ltctimegt // defines
time() using namespace std void main( )
srand( time(0) ) cout ltlt "Five random numbers
between 0 and 9\n\n" for (int i 1 i lt 5
i) cout ltlt rand()10 ltlt " "
Five random numbers between 0 and 9 9 1 2 1 2
33
Scope and Lifetime of Variables
34
Scope of Variables
  • The Scope of a variable is the region of program
    code where it is legal to use that variable for
    any purpose
  • C has two types of scopes
  • global/file scope
  • local/block scope

35
Global Scope
  • The scope of an identifier declared outside any
    block
  • Scope extends from point of declaration
    throughout the rest of the file
  • All functions have global scope

36
Local Scope
  • The scope of an identifier declared inside a
    block (including function parameters)
  • Scope extends from the point of the declaration
    to the end of the block
  • An identifiers scope does not include any nested
    block that contains a locally declared identifier
    with the same name

37
Local Scope
  • C allows multiple variables with same name
  • When an expression refers to a variable, the
    compiler first checks the local declarations
  • If the variable isnt local, compiler works
    outward through each level of nesting until it
    finds a variable with same name
  • Any variable with the same name declared at a
    level further out is never reached

38
A bad program!
  • int i 3 // global i
  • float MyFunction(int i) // function prototype
  • void main( )
  • i 4 // assignment to the global i
  • int i 15 // local i hides the global
    definition
  • i 17 // assigns to the local i
  • int i // yet another i
  • i 34 // assigns to the i from previous
    line
  • cout ltlt MyFunction(3)
  • float MyFunction(int i) // parameter i hides
    global i
  • i 34 // referring to
    parameter i
  • return i 2

39
Explicitly Specifying Global Scope
  • To refer to global or file scope variables where
    their definition is hidden by the local scope,
    use the operator

int i void main() int i i 3
//refers to local i i 4 //refers to
global i
40
Lifetime of a variable
  • The lifetime of a variable is the time during
    program execution when a variable actually has
    memory allocated to it
  • Lifetime of global scope variables
  • Lifetime of block (local) scope variables

41
Lifetime of Global Variables
  • Lifetime of global scope variables is the
    lifetime of the entire program
  • Their memory is allocated when program begins
    executing
  • Global variables are alive as long as the
    program is executing
  • Their memory is deallocated when the entire
    program terminates

42
Lifetime of Local Variables
  • Lifetime of block (local) scope variables is
    lifetime of the block
  • Their memory is allocated when execution enters
    the block
  • Local variables are alive while the block is
    executing
  • Their memory is deallocated when execution exits
    the block

43
Automatic vs. Static Variables
  • Memory for an automatic variable is allocated at
    block entry and deallocated at block exit
  • Memory for a static variable remains allocated
    throughout execution of the entire program
  • By default local variables are automatic
  • It is possible to have a static local variable
  • The reserved word static must be used in
    declaration

44
Static and Automatic Local Variables
  • void MyFunction( int x )
  • static int count 1 // initialized only once
  • int area 0 // initialized each time
  • area x x
  • cout ltlt "Square " ltlt count ltlt " " ltlt area ltlt
    endl
  • count
  • return

45
Pass-by-valuePass-by-reference
46
Passing arguments
  • Arguments can be passed in two ways
  • Pass-by-value
  • Pass-by-reference

47
Pass-by-value
  • The value of an argument is passed to the
    function when it is called.
  • The argument can be a variable identifier,
    constant, or expression.
  • By default, parameters of basic types (like int,
    char, float, double) are always value parameters,
    unless you do something to change that.

48
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
49
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
50
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
51
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
52
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
53
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
54
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
55
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
56
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
57
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
58
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
59
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
60
Pass-by-reference
  • The memory address of an argument is passed to
    the function when it is called.
  • Changes to a reference argument affect the actual
    variable passed.
  • The argument must be a variable identifier.
  • To get a reference parameter you need to place
    after the type in the function heading and
    prototype.

61
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
62
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
63
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
64
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
65
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
66
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
67
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
68
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
69
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
70
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
71
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
72
Example
int Calculate(int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (int myArg1, int myArg2) myArg1
10 myArg2 20 return myArg1 myArg2
73
Pass-by-reference Tips
  • Reference parameters should be used when you want
    your function to give a value to, or change the
    value of, a variable from the calling block
    without an assignment statement in the calling
    block.
  • When passing file streams to functions, always
    pass by reference since performing I/O operations
    modifies the stream.
  • Pass things that should not be changed by the
    function as value or const reference arguments.

74
Summary
75
Constant arguments to functions
  • Arguments which have a const in front of the type
    in the argument list are called constant
    arguments
  • Constant arguments may not be modified by the
    function
  • Argument may be both constant and reference
    (generally to save an expensive copy)

76
Example
int Calculate(const int arg1, int arg2) void
main() int i0,j1,k2,l3 cout ltlt
Calculate(i,j) ltlt i ltlt j ltlt endl cout ltlt
Calculate(k,l) ltlt k ltlt l ltlt endl int
Calculate (const int myArg1, int myArg2)
myArg1 10 // illegal assignment myArg2
20 return myArg1 myArg2
Write a Comment
User Comments (0)
About PowerShow.com