The C Programming Language Chapter 8 Functions
Overview
Function Definition
The Return Statement
Arguments --- Call By Value
Function Invocation
Nested invocation and Recursion
Arrays as parameters
Storage classes of variables
The C Programming Language Chapter 8 Functions
§8.1 Overview
Modular programming
Taking a problem and breaking it into small,manageable
pieces is critical to writing large problems,
In C,the function construct is used to implement this
“top-down” method of programming,
File 1
Preprocessing directives
Declarations Statements
Function 1 Function n
File i File n
C program
Structure of C program
A program has and only has one main() function;
Program execution begins and finishes with main;
Functions ar defined as individual objects that can not be
nested.But they can call each other.
The C Programming Language Chapter 8 Functions
Sorts of functions
From the point of view of users
Standard function (library function)
provided by system
Function writed by users
From the function format
Function with parameters
Function without parameters
The C Programming Language Chapter 8 Functions
§8.2 Function Definition
type function-name( parameter declaration list )
{
declarations
statements
}
Newer style:
as function with parameters
int max( int x,int y )
{ int z;
z=x>y?x:y;
return(z);
}
as function with parameters
int max(int x,y)
{ int z;
z=x>y?x:y;
return(z);
}
as do-nothing function
dummy( )
{ }
is useful as a place holder
during program development
as function without parameters
printstar( )
{ printf(“**********\n”); }
or
printstar(void )
{ printf(“**********\n”); }
Function body
Valid identifier
Returne-type by the function
If omitted,then it is int by default.
If no value is returned,then the type is void
The C Programming Language Chapter 8 Functions
type function-name( parameter list )
parameter declarations
{
declarations
statements
}
Traditional style
as function with parameters
int max(x,y)
int x,y;
{ int z;
z=x>y?x:y;
return(z);
}
The C Programming Language Chapter 8 Functions
§8.3 The Return Statement
Format return( expression )
or return expression ;
or return ;
Function,The return statement is the mechanism for
returning a value from the called function to the calling
function.
Specifications:
There can be zero or more return statements in a function;
If there is no return statement,then control is passed back
to the calling environment when the closing brace } is
encountered;
The expression will be converted,if necessary,to the
return type of the function,
Be notice to the functions needn’t returned value,
as function without returned value
void swap(int x,int y )
{ int temp;
temp=x;
x=y;
y=temp;
}
The C Programming Language Chapter 8 Functions
printstar()
{
printf("**********");
}
main()
{ int a;
a=printstar();
printf("%d",a);
}
Exp,return garbage
output10
void printstar()
{ printf("**********");
}
main()
{ int a;
a=printstar();
printf("%d",a);
}
Compiling error
The C Programming Language Chapter 8 Functions
Exp,The expression will be converted to the return type of the
function as specified in the function definition,
main()
{ float a,b;
int c;
scanf("%f,%f",&a,&b);
c=max(a,b);
printf("Max is %d\n",c);
}
int max(float x,float y)
{ float z;
z=x>y?x:y;
return(z);
}
The C Programming Language Chapter 8 Functions
§8.4 Arguments --- Call By Value
Parameter(formal argument) and Argument (actual argument)
parameter variables named in the parenthesized list in a
function definition;
argument the value used in a call of the function.
c=max(a,b); main
max max(int x,int y)
{ int z;
z=x>y?x:y;
return(z);
}
Exp:compare two numbers and output the maxmain()
{ int a,b,c;
scanf("%d,%d",&a,&b);
c=max(a,b);
printf("Max is %d",c);
}
max(int x,int y)
{ int z;
z=x>y?x:y;
return(z);
}
arguments
parameters
The C Programming Language Chapter 8 Functions
Specifications:
Arguments must have definit value;
Type of the parameter must be specified in the function
definition;
Typically,the arguments match in number and type the
parameters ;
The arguments will be converted,if necessary,to the
type of the parameters;
The called function is given the values of its arguments
in temporary variables rather than the originals.So the
called function cannot directly alter a variable in the
calling function.(Call-By-Value)
The C Programming Language Chapter 8 Functions
Exp,x3
#include <stdio.h>
float cube(float x)
{ return(x*x*x);
}
main()
{ float a,product;
printf("Please input value of a:");
scanf("%f",&a);
product=cube(a);
printf(”Cube of %.4f is %.4f\n",a,product);
}
x
a
product
1.2
1.2
1.728
The C Programming Language Chapter 8 Functions
7 11x,y:beginning
finish 7 11x,y:
Exp,exchange two numbers
/*ch7_2.c*/
#include <stdio.h>
main()
{ int x=7,y=11;
printf("x=%d,\ty=%d\n",x,y);
printf("swapped:\n");
swap(x,y);
printf("x=%d,\ty=%d\n",x,y);
}
swap(int a,int b)
{ int temp;
temp=a; a=b; b=temp;
}
calling
7 11a,b:
7 11x,y:
swap,7 11x,y:
11 7a,b:
temp
The C Programming Language Chapter 8 Functions
§8.5 Function Invocation
Specifications
The arguments match in number and type the parameters;
Evaluating order of the arguments in the argument list
depends on the systemTurbo C right-to-left
function-name( argument list )
Forms of function Invocation
Function as statement,as printstar();
printf(“Hello,World!\n”);
Function in expression,as m=max(a,b)*2;
Function as argument,as printf(“%d”,max(a,b));
m=max(a,max(b,c));
main()
{ int i=2,p;
p=f(i,++i);
printf("%d",p);
}
int f(int a,int b)
{ int c;
if(a>b) c=1;
else if(a==b) c=0;
else c=-1;
return(c);
}
main()
{ int i=2,p;
p=f(i,i++);
printf("%d",p);
}
int f(int a,int b)
{ int c;
if(a>b) c=1;
else if(a==b) c=0;
else c=-1;
return c);
}result0 result1
The C Programming Language Chapter 8 Functions
Functions should be declared before they are used;
Tells the compiler the number and type of arguments and the
type of the function;
Function prototypes is different from Function definitions;
Function prototypes occurs in or outside the function
Function prototypes can be omitted,when:
the return type of the function is int or char;
The called function is defined before the calling funtion,
type function-name(parameter type [parameter1],….,);
Function Declarations (Function Prototypes):
The C Programming Language Chapter 8 Functions
Exp,Function Declarations
main()
{ float a,b;
int c;
scanf("%f,%f",&a,&b);
c=max(a,b);
printf("Max is %d\n",c);
}
max(float x,float y)
{ float z;
z=x>y?x:y;
return(z);
}
the return type of the function is int,so
the function declaration can be omitted
/*ch7_5.c*/
float add(float x,float y)
{ float z;
z=x+y;
return(z);
}
main()
{ float a,b,c;
scanf("%f,%f",&a,&b);
c=add(a,b);
printf("sum is %f",c);
}
The called functi n is defined
before the calling funtion,so the
function declaration can be omitted
/*ch7_5.c*/
main()
{ float add(float,float); /*function declaration*/
float a,b,c;
scanf("%f,%f",&a,&b);
c=add(a,b);
printf("sum is %f",c);
}
float add(float x,float y)
{ float z;
z=x+y;
return(z);
}
The C Programming Language Chapter 8 Functions
#include <stdio.h>
long sum(int a,int b);
long factorial(int n);
main()
{ int n1,n2;
long a;
scanf("%d,%d",&n1,&n2);
a=sum(n1,n2);
printf("a=%1d",a);
}
long sum(int a,int b)
{
long c1,c2;
c1=factorial(a);
c2=factorial(b);
return(c1+c2);
}
long factorial(int n)
{ long rtn=1;
int i;
for(i=1;i<=n;i++)
rtn*=i;
return(rtn);
}
long sum(int a,int b);
long factorial(int n);
preprocessor directive
function prototypes
definition
invocation
invocation
return value
parameters
arguments
The C Programming Language Chapter 8 Functions
Nested invocation
In C functions,there are nested invocations rather than
nested definitions.
main( )
invoke a
finish
a b
invoke b


§8.5 Nested invocation and Recursion
The C Programming Language Chapter 8 Functions
Exp,Here are 3 numbers,compute max – min =?
#include <stdio.h>
int dif(int x,int y,int z);
int max(int x,int y,int z);
int min(int x,int y,int z);
void main()
{ int a,b,c,d;
scanf("%d%d%d",&a,&b,&c);
d=dif(a,b,c);
printf("Max-Min=%d\n",d);
}
int dif(int x,int y,int z)
{
return max(x,y,z)-min(x,y,z);
}
int max(int x,int y,int z)
{ int r ;
r=x>y? x,y ;
return(r>z? r,z); }
int min(int x,int y,int z)
{ int r;
r=x<y? x,y;
return(r<z? r,z) ; }
main( )
invoke dif
output
finish
dif max
invoke max
invoke min min
The C Programming Language Chapter 8 Functions
Exp:Using the method of chord-cut to find the root of the equation.
080165 23 xxx
)()(
)()(
12
1221
xfxf
xfxxfxx

x
y
f(x)
0
x1
x2
x
f(x1)
f(x2)
The C Programming Language Chapter 8 Functions
connect f(x1) and f(x2),find the point of
intersection x with axes X.
input x1,x2,compute f(x1),f(x2)
until f(x1) and f(x2) have different sign
y=f (x),y1=f (x1)
y,y1have the same signs
T F
x1=x y1=y x2=x y2=y
until |y|<?
root=x output root
root
main( )
invoke root
output root x
finish
root xpoint
invoke xpoint invoke f
f
#include <math.h>
float f (float x)
{ float y;
y=((x-5.0)*x+16.0)*x-80.0;
return(y);}
float xpoint(float x1,float x2)
{float x;
x=(x1*f(x2)-x2*f(x1))/(f(x2)-f(x1));
return(x);}
float root(float x1,float x2)
{ int i; float x,y,y1,y2;
y1=f(x1);
do { x=xpoint(x1,x2); y=f(x);
if(y*y1>0){ y1=y;x1=x;}
else {y2=y;x2=x;}
}while(fabs(y)>=0.0001);
return(x); }
main()
{ float x1,x2,f1,f2,x;
do{printf("input x1,x2:\n");
scanf("%f,%f",&x1,&x2);
f1=f (x1);
f2=f (x2);
}while(f1*f2>=0);
x=root(x1,x2);
printf(" root is %8.4f",x);}
The C Programming Language Chapter 8 Functions
Recursion
A function is said to be recursive if it calls itself,either
directly or indirectly.
f( )
calls f calls f2 calls f1
f1( ) f2( )
int f(int x)
{ int y,z;
……
z=f(y);
…….
return(2*z);
}
int f1(int x)
{ int y,z;
……
z=f2(y);
…….
return(2*z);
}
int f2(int t)
{ int a,c;
……
c=f1(a);
…….
return(3+c);
}
The C Programming Language Chapter 8 Functions
Exp,compute n!



)1()!1(
)1,0(1!
nnn
nn
#include <stdio.h>
int fac(int n)
{ int f;
if(n<0) printf("n<0,data error!");
else if(n= =0||n= =1) f=1;
else f=fac(n-1)*n;
return(f);
}
main()
{ int n,y;
printf("Input a integer number:");
scanf("%d",&n);
y=fac(n);
printf("%d! =%15d",n,y);
}
The C Programming Language Chapter 8 Functions
Exp,Compare two arrays
4
3
2
1
0
5
a
56
23
12
10
76
88
4
3
2
1
0
5
b
21
23
43
98
66
54
n=0
m=0
k=0
i
n=0
m=0
k=1
i
n=0
m=1
k=1
i
n=1
m=1
k=1
i
n=1
m=1
k=2
i
n=2
m=1
k=2
i
n=3
m=1
k=2
§8.7 Arrays as parameters
Array elements as parameters(call-by-value)#include <stdio.h>main()
{ int a[10],b[10],i,n=0,m=0,k=0;
printf("Enter array a:\n");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
printf("Enter array b:\n");
for(i=0;i<10;i++)
scanf("%d",&b[i]);
for(i=0;i<10;i++)
{ if(large(a[i],b[i])==1) n=n+1;
else if(large(a[i],b[i])==0) m=m+1;
else k=k+1;
}
/* Output */
}
int large(int x,int y)
{ int flag;
if(x>y) flag=1;
else if(x<y) flag=-1;
else flag=0;
return(flag);
}
The C Programming Language Chapter 8 Functions
Array name as parameter call-by-reference (address)
When the name of an array is used as an argument,the
value passed to the function is the location or address
of the beginning of the array--there is no copying of
array elements.
By subscripting this value,the function can access and
alter any element of the array.
The length of the array is not necessary in parameters
since its size is set in arguments.
The C Programming Language Chapter 8 Functions
Exp,the average score of the students
#include <stdio.h>
float average(int stu[10],int n);
void main()
{int score[10],i;
float av;
printf("Input 10 scores \n");
for( i=0; i<10; i++ )
scanf("%d",&score[i]);
av=average(score,10);
printf("Average is %.2f",av);
}
float average(int stu[10],int n)
{ int i;
float av,total=0;
for( i=0; i<n; i++ )
total += stu[i];
av = total/n;
return av;
}
use array name as argument
define an array as parameter?int stu[ ]
.
.
2
1
0
9
score
56
23
12
….
….
88
stu
The C Programming Language Chapter 8 Functions
Exp,compare array elements as parameter
with array name as parameter
1
2
a
before
invocation
a[0]
a[1]
1
2
a
invoke
a[0]
a[1]
1
2
x
y
2
1
x
y
exchange
1
2
a
return
#include <stdio.h>
void swap1(int x,int y)
{ int z;
z=x; x=y; y=z;
}
main()
{ int a[2]={1,2};
swap1(a[0],a[1]);
printf("a[0]=%d\na[1]=%d\n",a[0],a[1]);
}
call-by-value
The C Programming Language Chapter 8 Functions
1
2
a
before
invocation
1
2
ax
invoke
2
1
ax
exchange
2
1
a
return
Exp,compare array elements as parameter
with array name as parameter
#include <stdio.h>
void swap2(int x[])
{ int z;
z=x[0]; x[0]=x[1]; x[1]=z;
}
main()
{ int a[2]={1,2};
swap2(a);
printf("a[0]=%d\na[1]=%d\n",a[0],a[1]);
}
call-by-reference
The C Programming Language Chapter 8 Functions
Exp,get the sum of the numbers of each row(two-dimensional array)
get_sum_row(int x[][3],int result[],int row,int col)
{ int i,j;
for(i=0;i<row;i++)
{ result[i]=0;
for(j=0;j<col;j++)
result[i]+=x[i][j];
}
}
main()
{ int a[2][3]={3,6,9,1,4,7};
int sum_row[2],row=2,col=3,i;
get_sum_row(a,sum_row,row,col);
for(i=0;i<row;i++)
printf("The sum of row[%d]=%d\n",i+1,sum_row[i]);
}
3
1 4
6
7
9
a sum_row
18
12
x
result
The C Programming Language Chapter 8 Functions
8.8 Storage classes of variables
Every variable in C has two attributes:
type and storage class.
The four storage classes are:
auto extern register static
Declarations of variable,
[storage class] type variable list ;
as,int sum;
auto int a,b,c;
register int i;
static float x,y;
The C Programming Language Chapter 8 Functions
Local variables and global variables
Local variables ---internal variables
Describes the variables defined inside the functions;
The variables are accessible only within the function in
which they are declared;
Different functions can use the same identifiers,because
they are assigned different storage;
Parameters are local variables;
Can define variables in compound statements;
Local variables can be,auto register static
( auto by default)
float f1(int a)
{ int b,c;
…….
}
char f2(int x,int y)
{ int i,j;
……
}
main()
{ int m,n;
…….
}
a,b,c
x,y,i,j
m,n
Result 5 4 3 2 1
Exp,variables in the compound statement
#define N 5
main()
{ int i;
int a[N]={1,2,3,4,5};
for(i=0;i<N/2;i++)
{ int temp;
temp=a[i];
a[i]=a[N-i-1];
a[N-i-1]=temp;
}
for(i=0;i<N;i++)
printf("%d ",a[i]);
}
p:same identifiers in different functions
main()
{ int a,b;
a=3;
b=4;
printf("main:a=%d,b=%d\n",a,b);
sub();
printf("main:a=%d,b=%d\n",a,b);
}
sub()
{ int a,b;
a=6;
b=7;
printf("sub:a=%d,b=%d\n",a,b);
}
Result
main:a=3,b=4
sub:a=6,b=7
main:a=3,b=4
The C Programming Language Chapter 8 Functions
Declaration of an external variable announces the properties
of the variable(primarily its type);definition also causes
storage to be set aside;
If external variables and internal variables use the same
identifiers,external variables may be masked;
Global variables---external variables
Global variables are defined outside of any functions,and are
thus available to many functions;
The scope of an external variable lasts from the point at which
it is declared to the end of the file being compiled,>
>
>
If an external variable is to be referred to before it is defined
or it is defined in a different source file from the one where it
is being used,then an extern declaration is mandatory,
extern type variable list >
The C Programming Language Chapter 8 Functions
float max,min;
float average(float array[],int n)
{ int i; float sum=array[0];
max=min=array[0];
for(i=1;i<n;i++)
{ if(array[i]>max) max=array[i];
else if(array[i]<min) min=array[i];
sum+=array[i];}
return(sum/n);
}
main()
{ int i; float ave,score[10];
/*Input */
ave=average(score,10);
printf("max=%6.2f\nmin=%6.2f\n
average=%6.2f\n",max,min,ave);
}
scope
max
min
The C Programming Language Chapter 8 Functions
int p=1,q=5;
float f1(int a)
{ int b,c;
…….
}
int f3()
{…..
}
char c1,c2;
char f2(int x,int y)
{ int i,j;
……
}
main()
{ int m,n;
…….
}
Scope of c1,c2
Scope of p,q
extern char c1,c2;
extern char c1,c2;
c1,c2
sco
pe
c1,c2
sco
pe
The C Programming Language Chapter 8 Functions
Exp,definition and declaration
int max(int x,int y)
{ int z;
z=x>y?x:y;
return(z);
}
main()
{ extern int a,b;
printf("max=%d",max(a,b));
}
int a=13,b=-8;
Resultmax=13
extern int a,b;
int max()
{ int z;
z=a>b?a:b;
return(z);
}
main()
{ printf("max=%d",max());
}
int a=13,b=-8;
The C Programming Language Chapter 8 Functions
int a=3,b=5;
max(int a,int b)
{ int c;
c=a>b?a:b;
return(c);
}
main()
{ int a=8;
printf("max=%d",max(a,b));
}
Exp:external variables and internal variables
Result max=8
The C Programming Language Chapter 8 Functions
Dynamic variables and static variables
Dynamic variables come into existence when the function
in which they are defined is entered,and disappear when it is
left; (auto)
Static variables remain in existence,they provide permanent
storage
Specifications,
Local variables are auto by default;
variables are dynamic;
The static applied to an external variable limits the scope of
that object to the rest of the source file being compiled;it can
also be applied to internal variables to retain their previous
value when the function is reentered;
Extern can be used to extend the scope of the external
variables.
The C Programming Language Chapter 8 Functions
Exp,file1.c
int a;
main( )
{ …….
…….
f2;
…….
f1;
…….
}
f1( )
{ auto int b;
………
f2;
……..
}
f2( )
{ static int c;
………
}
C scope
b scope
a scope main f2 f1main f1f2 main
a lifetime:
b lifetime:
c lifetime,
The C Programming Language Chapter 8 Functions
Exp,the scope of auto variable
main()
{ int x=1;
void prt(void);
{ int x=3;
prt();
printf(“2nd x=%d\n”,x);
}
printf(“1st x=%d\n”,x);
}
void prt(void)
{ int x=5;
printf(“3th x=%d\n”,x);
}
Result
3th x=5
2nd x=3
1st x=1
scope of x=1
scope of x=1
scope of x=3
scope of x=5
The C Programming Language Chapter 8 Functions
main()
{ void increment(void);
increment();
increment();
increment();
}
void increment(void)
{ int x=0;
x++;
printf(“%d\n”,x);
}
Exp:static local variable can retain their previous value when
the function is reentered
Result 1
1
1
main()
{ void increment(void);
increment();
increment();
increment();
}
void increment(void)
{ static int x=0;
x++;
printf(“%d\n”,x);
}
Result 1
2
3
The C Programming Language Chapter 8 Functions
main()
{ void gx(),gy();
extern int x,y;
printf(“1,x=%d\ty=%d\n”,x,y);
y=246;
gx();
gy(); }
void gx()
{ extern int x,y;
x=135;
printf(“2,x=%d\ty=%d\n”,x,y);
}
int x=2,y=3;
void gy()
{ printf(“3,x=%d\ty=%d\n”,x,y);}
Exp:use extern to extend the scope of the external variables
Result
1,x=2 y=3
2,x=135 y=246
3,x=135 y=246
The C Programming Language Chapter 8 Functions
Exp:use external variables of other files
int global;
extern float x;
main()
{ int local;
.
.
.
}
extern int global;
static int number;
func2()
{,
.
.
}
float x;
static int number;
func3()
{ extern int global;
.
.
.
}
file1.c
file2.c
file3.c