Title: Functions
1Functions
2Functions
- 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
3Why 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
4Function concept in math
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.
5What 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).
6Function 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.
7Function 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
8Function 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
9Function Declaration
void CalculateSquare(void) void main(void)
cout ltlt "CALCULATING SQUARES\n"
CalculateSquare() cout ltlt "\nWe are
done!\n"
10Function 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.
11Function Call
void CalculateSquare(void) void main(void)
cout ltlt "CALCULATING SQUARES\n"
CalculateSquare() cout ltlt "\nWe are
done!\n"
12Example 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!
13Return 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)
14The 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
15Function 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!
16Passing 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
17Arguments 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
18Example
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
19Assignment
- 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).
20Local/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
21Example
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
22Example
Enter people and pay 5 1501.5 Average pay is
300.30
23Existing 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
24Common library functions
25Terminating 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
26Generating 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
27Example
- 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
28Seeding 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
29Example
- 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
30Seeding 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) )
31Example
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
32Controlling 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
33Scope and Lifetime of Variables
34Scope 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
35Global 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
36Local 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
37Local 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
38A 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
39Explicitly 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
40Lifetime 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
41Lifetime 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
42Lifetime 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
43Automatic 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
44Static 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
45Pass-by-valuePass-by-reference
46Passing arguments
- Arguments can be passed in two ways
- Pass-by-value
- Pass-by-reference
47Pass-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.
48Example
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
49Example
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
50Example
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
51Example
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
52Example
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
53Example
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
54Example
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
55Example
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
56Example
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
57Example
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
58Example
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
59Example
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
60Pass-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.
61Example
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
62Example
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
63Example
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
64Example
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
65Example
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
66Example
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
67Example
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
68Example
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
69Example
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
70Example
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
71Example
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
72Example
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
73Pass-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.
74Summary
75Constant 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)
76Example
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