You are on page 1of 15

C Programming

Functions

Session Objectives
Ø Functions
Ø Built in functions
Ø User defined functions
Ø Recursion

Page 5.1 © TransEd Release 3.1


C Programming

Functions
A function is a self-contained subroutine/program segment that carries out some specific well-defined
task. C supports use of built in library functions, which are used to carry out commonly used
operations or calculations. C also allows programmers to define their own functions called user
defined functions.

Advantages of functions
Ø Usage of functions ensures modular approach to program development. When many programs
require a particular group of instructions to be accessed repetitively from different parts of the
program, the repeated functions can be placed within a single function. This function can be
accessed whenever and wherever required.

Ø Functions avoid the need for redundant programming of the same instructions.

Ø Logical clarity results from the decomposition of a program. Programs consisting of functions are
easier to write and debug and their logical structure is very apparent than that of programs that
lack that structure, especially in case of lengthy, complicated programs.

Ø Use of functions enable programmer to build a customized library of frequently used routines.

Classification of functions
Every C program consists of one or more functions. These functions can be categorized into

Ø Built in functions
Ø User defined functions

Built in functions are not required to be written by the user and is readily available in a header file,
Mostly used built in functions are main, printf, scanf. strcpy(),strlen(),strcmp() are also built in
functions which are part of the header file string.h . Main is the first executed function in a C program
from where other functions can be called. A program can consist of multiple functions.

User defined functions are functions written by the user. It is possible to write a program using only
the main funciton. This approach can lead to lot of problems. User defined functions are inevitable
when some type of operation or calculation is repeated at many points throughout the program.
Consider the case of using the factorial of a number at several points in a program.

Working with user defined functions


Usage of functions in programs entails three things:

Ø Function declaration
Ø Function definition
Ø Call to the function

Page 5.2 © TransEd Release 3.1


C Programming

Function declaration
Functions are subroutines that take in parameters or arguments,perform some processing on them and
return a value. Functions, in other words , allow bi-directional transmission of information.

When user defined functions are used in a program, it is a better practice to declare a prototype of the
function along with variable declarations. Such declarations are also called forward-declarations or
function prototypes. C does not expect a function declaration when the function returns an int. For all
other functions, the function declaration or prototype is a must. On the other hand, if a function returns
a value other than an integer and is not declared but used, the compiler automatically assumes that to
be an int returning function.

The general form of function declaration is:

Type functionname(parameterlist);

Type àrefers to the datatype of the return value


Functionname àrefers to the name of the function
Parameterlistàrefers to the list of datatypes of the arguments or
parameters separated by commas

Consider the case of writing declaration for a function, which is expected to take two integer
arguments and perform the addition of both the numbers and return the result. The function
declaration for the above would be as follows:

int sum(int, int);

Data type of the return Name of the function Two integer type arguments to be passed
value

Functions that do not return any value are called void functions.When declaring a void function ,the
keyword void can be used for specifying the datatype for the return value. Consider a function that is
expected to take two float arguments but does not return any value. The function declaration for the
above would be:

void func1(float,float);

Function definition
While function prototype involves stating the datatype of the return values and arguments along with
the function name, Function Definition involves writing the code of the function. The form of defining
a function is as follows:

Type functionname(parameterlist)
{
executable statements
return (expression);
}

Page 5.3 © TransEd Release 3.1


C Programming

type à represents the data type of the value which is returned.


Functionname à represents the function name
Parameterlist à represents a list of variables that are to hold the values passed to the
function.
Executable statements à represents the body or code of the function.
Return expression à represents the return value in the expression and also return of control.

The parameters that are specified in the function definition are called formal parameters. These
formal parameters allow information to be transferred from the calling portion of the program to the
function.The names of the formal arguments may be the same as the names of other identifiers that
appear outside the function definition.

Consider the above said case of writing a function definition for the function declared above to
compute the sum of two integers.

int sum(int a,int b)


{
int c;
c=a+b;
return c;
}

The formal argument list specifies the datatype of the variables along with the variable names,the data
types of the arguments being int and the respective variable names a,b.
int c; Here c refers to declaring a local variable that is available within the function sum alone.
This variable is declared to hold the return value.
c=a+b; The sum of the variables a and b is calculated and the result stored in c.
return c; return keyword is used to return the value of c to the calling program.

Return statement can take one of the following forms:


return;
Or
return (expression);
Return can be given without an expression in which case the control of execution is returned to the
calling program.

Call to the function


A function can be called by using the function name in a statement. Consider calling the sum()
function discussed earlier.

main()
{
int a,b,c;
printf(“enter a value for a”);
scanf(“%d”,&a);
printf(“enter a value for b”);
scanf(“%d”,&b);
c=sum(a,b);/*sum function is called by passing two
arguments a and b*/
printf(“sum is %d”,c);
}

Page 5.4 © TransEd Release 3.1


C Programming

When the compiler encounters a function call, the control is transferred to the function sum(a,b). Here
a and b are called actual parameters. The sum function is executed line by line as described and a
value is returned when the return statement is encountered inside the sum function. The return value is
assigned to c.

: HANDS-ON

#include<stdio.h>
/* creating and using a user defined function*/
main()
{
int a,b,c;
int sum(int,int);/*function declaration*/
printf(“enter a value for a”);
scanf(“%d”,&a);
printf(“enter a value for b”);
scanf(“%d”,&b);
c=sum(a,b);/*sum function is called by passing two
arguments a and b*/
printf(“sum is %d”,c);
}
int sum(int a, int b)
{
int c;/*local variable*/
c=a+b;
return c;
}

Nesting of functions
C permits nesting of functions. Consider the case of calculating net pay of an employee. The net pay is
calculated as
Grosspay – tax deduction
The grosspay is calculated as
Basic + HRA + DA – PF.
Consider writing two functions netpay(), grosspay() for the above purpose. The hierarchy of calling
functions is diagramatically represented below:

Page 5.5 © TransEd Release 3.1


C Programming

main()
{

x=netpay(arguments);

}
netpay(arguments)
{
executable statements
gpay=grosspay(arguments)
npay=gpay - tax;
return npay;
}
grosspay(arguments)
{
executable statements
return gpay;
}
In the diagram above, grosspay() function call is nested withing netpay() function call which is nested
in main().

: HANDS-ON

#include<stdio.h>
/* program with nested functions*/
float netpay(float,float,float,float,float);
float grosspay(float,float,float,float);
main()
{
char ename[20];
float basic,hra,da,pf,npay,taxperc;
printf(“enter employee name”);
fflush(stdin);
scanf(“%s”,ename);
printf(“enter the basic,hra,da,pf,tax percentage”);
fflush(stdin);
scanf(“%f %f %f %f %f”,&basic,&hra,&da,&pf,&taxperc);
npay=netpay(basic,hra,da,pf,taxperc);
printf(“netpay after tax for %s is %f”,ename,npay);
}
float netpay(float f1,float f2,float f3,float f4,float f5)
{
float npay,gpay;
gpay=grosspay(f1,f2,f3,f4);
npay=gpay-(gpay*f5/100);
return (npay);
}
float grosspay(float f1,float f2,float f3,float f4)
{
float gp;
gp=f1+f2+f3-f4;
return (gp);
}

Page 5.6 © TransEd Release 3.1


C Programming

Functions with Arrays


It is possible to pass values of an array to a function like passing variables to functions. In order to
pass an array to a function,it is sufficient to list the name of the array without any subscripts, and the
size of the array as arguments. For example the call

Least(x,n);

Will pass all the elements in the array x of size n. The function declaration must be accordingly
given.consider the following Hands-on which uses a function that has array as argument.

: HANDS-ON

#include<stdio.h>
/* program with function using array parameter*/
main()
{
int least();
int arr[]={20,30,5,17,13};
printf(“%d\n”,least(arr,5));/* least function with array arr as
parameter, 5 size of the array*/

}
int least(int a[],int n)
{
int x;
int min;
min=a[0];
for (x=0;x<n;x++)
if (a[x] < min)
min=a[x];
return min;
}

Recursion
Recursion is a process by which a function calls itself repeatedly, until some specified condition has
been satisfied. This process is used for repetitive conditions in which each action is stated in terms of a
previous result. Iterative problems can be written in this form.

For a problem to be handled through recursion two conditions must be satisfied:

Ø Problem must be written in a recursive form.


Ø Problem statement must include a stopping condition

Calculating factorial of a number can be done using Recursion.

Page 5.7 © TransEd Release 3.1


C Programming

: HANDS-ON

#include<stdio.h>
/* program with recursive function*/
main()
{
int no;
long int factorial(int);
/*accept the number*/
printf(“enter the number”);
scanf(“%d”,&no);
/*calculate factorial*/
printf(“factorial of %d is %ld”,no,factorial(no));
}
long int factorial(int n)
{
if (n<=1)
return(1);
else
return(n * factorial(n-1));
}

In the above program, main() reads an integer value no and calls the recursive function factorial. Long
int is specified as datatype for the return value, since factorials are large integer quantities even for
modest values of n. The function factorial calls itself recursively, with an actual argument (n-1) that
decreases in magnitude for each successive call. The recursive calls terminate when the value of the
actual argument becomes equal to 1. When the program is executed, function factorial() will be
accessed repeatedly, once in main() and (n-1) times within itself.

If a recursive function contains local variables, a different set of local variables will be created during
each call. Names of the local variables will be the same as declared within the function.However the
variables will represent a different set of values each time the function is executed. Each set of values
will be stored in a stack , so that they will be available as the recursive process unwinds.

Storage Classes
There is a scope and lifetime for a variable, which are defined in C programming language. It all
depends on the storage class a variable may assume. A variable in C can have any one of the four
storage classes.
1. Automatic variable
2. External variables
3. Static variables
4. Register variables.

The scope of variables determines over what part(s) of the program a variable is actually available for
use. The lifetime or longevity refers to the period during which a variable retains a given value during
execution of a program. The variables may also be categorized depending on the place of their
declaration as internal (local) or external (global). Internal variable are those which are declared
within a function and external variable are declared outside of any function.

Page 5.8 © TransEd Release 3.1


C Programming

Automatic Variables
Automatic variables are declared inside a function and this is the default storage class assumed when
no storage class is specified. They are created when the function is called and destroyed automatically
when the function is exited.

For example the storage class of the variables number1 and number2 in the following code snippet is
automatic

main()
{
auto int number1;
int number2;
.
.
}
One important feature of automatic variable is that their value cannot be changed accidentally by what
happens in some other function in the program. This assures that a variable may be declared and can
use the same variable name in different functions in the same program without causing any confusion
to compiler.

: HANDS-ON

#include <stdio.h>
int main()
{
auto int a;
a = 10;
{
auto int a , b;
a = 12;
b = a +2;
printf(“%d %d\n”, a, b);
}
printf(“%d\n”, a);
/*printf(“%d\n”,b); error : variable b is not declared */
}

In the above code, the variable ‘a’ is declared twice. One within the main function code block and
another within a sub-code block. The life time a automatic variable is within the code block it is
declared.

: HANDS-ON

#include <stdio.h>
void display();
int main()
{

Page 5.9 © TransEd Release 3.1


C Programming

int a;
a = 10;
printf(“value of a in main %d\n”, a);
display();
printf(“value of a in main %d\n”,a);
}
void display()
{
int a;
a = 50;
printf(‘value of a in display %d \n”,a);
}

External Variables
Variables that are both alive and active throughout the entire program are known as external variables.
They are also known as global variables. These variables can be accessed by any function in the
program. External variables are declared outside a function.

For example the external declaration of integer count might appear as:
int count;
int main()
{
----
---
}
void function1()
{
---
--
}
void function2()
{
---
---
}

The variable count is available for use in all the functions in this program. In case a local variable and
a global variable have the same name, then the local variable will have precedence over the global one
in the function where it is declared. Unlike local variables the global variables are initialized to zero
by default.

For example:
int count;
int main()
{
count = 10;
---
---
}
void function1()
{

Page 5.10 © TransEd Release 3.1


C Programming

printf(“%d”, count); /*will display 10 - in this case */


--
}
void function2()
{
int count = 5;
count ++; /* only the local variable is affected
not the global variable */
---
}

External Declaration
One other aspect of a global variable is that it is visible only from the point of declaration to the end of
the program. For example, consider the following code snippet:

int main()
{
count = 5;
---
---
}
int count;
void function1()
{
count ++;
}

If the above code is compiled, the complier will issue error messages like
‘count’ undeclared
‘count’ used prior to declaration

This problem can be solved by declaring the variable with the storage class extern. For example

main()
{
extern int count; /* external declaration */
----
----
}
void function1()
{
extern int count; /* external declaration */
----
----
}
int count; /* definition */

Although the variable ‘count’ has been defined after both the functions, the external declaration of
‘count’ inside the function informs the compiler that ‘count’ is an integer type defined somewhere in
the program. The extern declaration does not allocate storage space for variables. An extern within a
function provides the type information to just that one function. The extern variable type information
has to be made available to all function within a file by pacing external declaration before any of
them.

Page 5.11 © TransEd Release 3.1


C Programming

For Example
extern int count ;
int main()
{
void function1();
-----
-----
function1();
}
void function1()
{
count += 3;
}
int count ;

Memory is allocated for the function like any other variable when the function is defined and type
information for the parameters are provided. Since functions are external by default, the function is
declared without the qualifier extern.
Therefore
void function1();
is equivalent to
extern void function1();

The function declaration outside of any functions behave the same way as variable declarations.

Use of extern in Multifile Program


In real-life programming environment, more than one source file may be compiled separately and
linked later to form an executable object code. This approach is vary useful because any change in
one file dose not affect other file thus eliminating the need for recompilation of the entire program.

Multiple source files can share a variable when it is declared as an external appropriately. Variables
that are shared by two or more files are global variables and therefore it must be declared accordingly
in one file and then explicitly defined as extern in other file. The following example illustrates the use
of extern declarations in multiple file.

: HANDS-ON

/* inccount.c */

int count; /* global variable */

void IncCount() /* function to increment the variable count */


{
count++;
}

/* main.c */
#include <stdio.h>
extern int count; /* count declared as external variable */
void IncCount();
void AnotherFunction();

Page 5.12 © TransEd Release 3.1


C Programming

int main()
{
IncCount();
printf(“count = %d\n”, count);
count = 7;
AnotherFunction();
}
void AnotherFunction()
{
IncCount();
printf(“count in Another Function : %d \n”, count);
}

Note
To compile the above program, commands are
$ cc –c incc.c <= create an object file for incc.c
$ cc –c main.c <= create an object file for main.c
$ cc incc.o main.o –o prog <= link object file and create output file prog.

Such compilation are known as Separate Compilation.

Static Variables
The value of a static variable persists until the end of the program. A variable can be declared static
using keyword static. Like
static int count;
static char option;
A static variable may be either an internal type or external type. The scope of internal static variable
extend up to the end of function in which they are defined. Internal static variables are similar to auto
variables, except that they remain in existence throughout the life of the program. Internal static
variables retain values between function calls. A static variable is initialized only once. It is never
initialized again. For example it can be used to count the number of calls made to a function.

: HANDS-ON

#include <stdio.h>
int main()
{
int k;
for( k=1; k <=3; k++)
stat();
}
void stat()
{
static int x = 0;
x = x + 1;
printf(“x = %d \n “, x);
}

Page 5.13 © TransEd Release 3.1


C Programming

When the stat function is called for the first time, the static x is initialized to 0 and then it is
incremented by 1. When the stat function is called for consecutive time, the x is not reinitialized but it
will retain the value and the retained value will be incremented.

EXPLORE

Declare the static variable as auto variable and check the output.

An external static variable is declared outside of all functions and is available to all the functions in
that program and restricted to be accessed only within the file unlike simple external variable which
can be accessed by other files. It is also possible to control the scope of a function similar to the
external variable. When a function is declared as static, then that function is accessible only with file
in which it is defined.

Register Variables
Registers are special storage areas within a computer’s central processing unit. The actual arithmetic
and logical operation that comprise a program are carried out within these registers. Normally, these
operations are carried out by transferring information from the computer’s memory to these registers,
carrying out the indicated operations, and then transferring the results back to the computer’s
memory. This general procedure is repeated many times during the course of a program’s execution.

Execution time can be reduced considerably if certain values can be stored within these registers
rather than in the computer’s memory. The value of register variables are stored within the central
processing units’ registers. A register variable can be declared using a keyword ‘register’.

For example:
register int a, b, c;

There can be only a few register variables within any one function. The exact number depends on the
particular computer and the specific C compiler. The scope of register variable is similar to automatic
variables. The address of (&) operator cannot be applied to register variables. Stating a variable as
register variable is just a suggestion to the compiler to treat the variable as register variable. Honoring
the variable as register variable depends on the cpu’s register availability. If the register variable is not
honored then it is treated as automatic variable.

F TOTAL RECALL

1. What is a function?
2. State the advantages of using functions.
3. State the three factors in creating and using functions.
4. What is the purpose of the return statement.
5. Explain the meaning of the following function declarations
int func1(int a);
char func2(void);
double func3(double a,double b);
6. Write the first line of function definition and the formal argument declarations for each of the
following situations:

Page 5.14 © TransEd Release 3.1


C Programming

Ø Function root accepting two integer arguments and returning a floating point result.
Ø Function inverse accepting a character and returning a long integer.
Ø Function process accepting an integer and two floating point numbers and returning a
double
Ø Precision quantity.
7. Explain Recursion.

REVIEW QUESTIONS

Fill up the blanks


1. The parameters that are specified in the function definition are called ______________.
2. Functions that do not return any value are called _____________ functions.
3. Functions can be categorized into ____________ and _____________.
4. __________ is a process by which a function calls itself repeatedly.
5. _________ functions are not required to be defined by the user.

True or False
1. The Called function cannot call the calling function.
2. A function can return more one value at a time.
3. The actual parameter data type can differ from the formal parameter data type.
4. Function need not be defined before calling the function.
5. Functions cannot return array.

Page 5.15 © TransEd Release 3.1

You might also like