Module 2
Module 2
Module 2
Functions
A function is a self-contained block of statements that perform a specific task of some
kind. Every C program can be thought of as a collection of these functions.
void message( )
{
printf ( "\ nwelcome to world of functions!!!" ) ;
}
1
2
Here, main( ) itself is a function and through it we are calling the function message( ).
When we say that main( ) ‘calls’ the function message( ), it means that the control passes
to the function message( ). The activity of main( ) is temporarily suspended; it falls
asleep while the message( ) function wakes up and goes to work. When all statements in
the message( ) function completed execution, the control returns to main( ), which comes
to life again and begins executing remaining code after the function call.(at the exact
point where it was suspended).
main( ) becomes the ‘calling’ function, whereas message( ) becomes the ‘called’
function.
A function gets called when the function name is followed by a semicolon. For
example,
main( )
{
message( ) ; //calls the function message
}
A function is defined when function name is followed by a pair of braces in which
one or more statements may be present. For example, message is defined as follows:
void message( )
{
printf ( "\nWelcome to functions!!" ) ;
}
A function can be called any number of times. For example,
main( )
{
message( ) ;
message( ) ;
}
void message( )
{
printf ( "\nWelcome to functions!!" ) ;
}
The order in which the functions are defined in a program and the order in which
they get called need not necessarily be same. For example,
main( )
{
2
3
message1( ) ;
message2( ) ;
}
void message2( )
{
printf ( "\nC Programming" ) ;
}
void Message1( )
{
printf ( "\ nWelcome to functions!!" ) ;
}
Function prototype
A function prototype is a declaration of a function that specifies the function's name and
type signature ( parameter types, and return type), but omits the function body.
Examples.
1. float square ( float ) ;
2. int add(int, int);
3. void message();
int add( int x, int y); // function prototype. int is the type of value returned from function
main()
{
3
4
int a,b,sum;
a=10;
b=100;
sum=add(a,b) // calling function with actual arguments a and b and
assigning the value returned from function
to the variable sum.
}
//function definition
int add(int x, int y) // formal arguments x and y
{
int s;
s=x+y;
return(s); // return sum to main program
}
Note:Variables declared in a function are not available to other functions in a program
In this program, from the function main( ) the values of a, b are passed on to the
function add( ), by making a call to the function add( ) and mentioning a, b in the
parentheses:
sum=add(a,b) ;
In the add( ) function these values get collected in three variables x, y
add (int x, int y)
Return Statement
The return statement serves two purposes:
(1) On executing the return statement it immediately transfers the control back to
the calling program.
(2) It returns the value present in the parentheses after return, to the calling
program. In the above program the value of sum of two numbers is being
returned.
If we want that a called function should not return any value, in that case, we must
mention so by using the keyword void as shown below.
void message( )
{
4
5
A function can return only one value at a time. Thus, the following statements are
invalid.
return ( a, b ) ;
return ( x, 12 ) ;
when values are passed to a called function the values present in actual
arguments are not physically moved to the formal arguments; just a copy of
values in actual argument is made into formal arguments.(Call by value)
So instead of passing the value of a variable, we can pass the location number
(also called address) of the variable to a function. Such function calls are called
‘calls by value’.
………………………………………………………………………………………
…
Eg. Different ways of using functions
#include<stdio.h>
void add();
// function prototype written at the beginning and similar to first line of function
//definition. Keyword void indicates nothing is returned from function
main()
{
add() // calling function
}
//function definition
void add()
{
int a,b,sum;
a=10;
b=100;
sum=a+b;
printf(”the sum=%d”,sum);
5
6
#include<stdio.h>
void add( int x, int y); // function prototype
main()
{
int a,b;
a=10;
b=100;
add(a,b) // calling function with actual arguments a and b
}
//function definition
void add(int x, int y) // formal arguments x and y
{
int sum;
sum=x+y;
printf(”the sum=%d”,sum);
return; // return statement transfers control back to main program
}
Within each function call, the no of actual arguments must be same as no of formal
arguments and each actual argument must be of the same datatype of the
corresponding formal argument.
While calling the function, value of each actual argument is transferred into function
and assigned to the corresponding formal argument.
------------------------------------------------------------------------------------------------
3. Functions with Arguments and Return value
Eg. Function for to find the sum of two integer values passed as arguments and return
the result to the main program
#include<stdio.h>
int add( int x, int y); // function prototype. Int is the type of value returned from
function
main()
{
int a,b,sum;
6
7
a=10;
b=100;
sum=add(a,b) // calling function with actual arguments a and b and
assigning the value returned from function
to the variable sum.
}
//function definition
int add(int x, int y) // formal arguments x and y
{
int s;
s=x+y;
return(s); // return sum to main program
}
…………………………………………………………………………………………
#include<stdio.h>
void funct1( int a, int b);
main()
{
int a,b;
a=10;
b=500;
printf(“before calling funct1: a=%d b=%d “, a,b);
funct1(a,b);
printf(“after calling funct1: a=%d b=%d “, a,b);
}
void funct1(int a, int b)
{
a=1; b=5;
printf(“within funct1: a=%d b=%d “, a,b);
return;
}
THE OUTPUT OF THIS PROGRAM WILL BE:
before calling funct1: a=10 b=500
within funct1: a=1 b=5
after calling funct1: a=10 b=500
7
8
Notice that a and b are unchanged in main after calling function. This illustrates that
the variables are local to the functions in which it is defined.
-------------------------------------------------------------------------------------------------------
Recursion
It is the process by which a function calls itself repeatedly until some specified
condition.
Eg. Factorial of a number
Note: factorial of 4, 4! = 4 * 3 * 2 * 1. This can be expressed as 4! = 4 * 3!
main()
{
int n,fact;
….
fact=factorial(n); //function call
}
int factorial(int x)
{
int f;
if(x==1)
f=1;
else
f=x*factorial(x-1);// call the function itself
return( f);
}
Stack is a Last in First Out data structure (LIFO) – means the last item stored on the
stack is the first item taken out from it- is used to implement recursion.
Visualisation of steps while recursive function gets called for finding 3!
8
9
………………………………………………………………………………………
Pointers
The data item can be accessed if we know the address/location of the data item. The
address of v can be determined by &v, where & is called the address operator.
The data item represented by v ie the value of v ( here 3) can be accessed by the
expression *pv, where * is called indirection operator. There fore *pv and v both
represents the same item
10
11
This declaration tells the compiler that pv is a pointer variable ie it will be used to
store the address of an integer value.
The address can be collected in pointer variable pv, by saying,
pv = &v ;
11
12
------------------------------------------------------------------------------------------------------
(x+1)
(x+2)
The C preprocessor
It is a program that processes our source program before it is passed to the
compiler.
The directives can be placed anywhere in a program but are most often placed at the
beginning of a program, before the first function definition.
There are essentially three uses of the preprocessor--directives, constants, and
macros.
Directives are commands that tell the preprocessor to skip part of a file, include
another file, or define a constant or macro. Directives always begin with a sharp sign
(#)
Define Constant
12
13
Suppose a constant like 3.1415 appears many times in your program. This value
may have to be changed some day to 3.141592. Ordinarily, you would need to go
through the program and manually change each occurrence of the constant.
However, if you have defined PI in a #define directive, you only need to make
one change, in the #define directive itself:
#define PI 3.141592
For eg PI has defined the value 3.14 which is used to calculate area of circle.
#include<stdio.h>
#define PI 3.14
main()
{
int a,r=10;
a=PI*r*r;
printf("%d",a);
}
You can see in the given example, we have defined a macro i.e SQUARE(x) x*x. Here
the macro determines the square of the given number.
#include <stdio.h>
#include <conio.h>
#define SQUARE(x) x*x
int main()
{
int i = 2;
int j= SQUARE(i);
printf("The value of j is: %d\n", j);
getch();
return 0;
}
13
14
Usually macros make the program run faster but increase the program size,
whereas functions make the program smaller and compact. If we use a macro
hundred times in a program, the macro expansion goes into our source code at
hundred different places, thus increasing the program size. On the other hand, if a
function is used, then even if it is called from hundred different places in the
program, it would take the same amount of space in the program.
But passing arguments to a function and getting back the returned value does take
time and would therefore slow down the program. This gets avoided with macros
since they have already been expanded and placed in the source code before
compilation.
No Macro Function
1 Macro
Function is Compiled
is Preprocessed
14
15
File inclusion
The preprocessor command for file inclusion looks like this:
#include <filename>
(eg #include <math.h>)
it simply causes the entire contents of filename to be inserted into the source code at
that point in the program.
It is common for the files that are to be included to have a .h extension. This
extension stands for ‘header file’, possibly because it contains statements which when
included go to the head of your program. The prototypes of all the library functions
are grouped into different categories and then stored in different header files.
For example prototypes of all mathematics related functions are stored in the header
file ‘math.h’, prototypes of console input/output functions are stored in the header file
‘conio.h’, and so on.
……………………………………………………………………………………………..
The arguments that we pass on to main( ) at the command prompt are called
command line arguments.
The function main( ) can have two arguments, traditionally named as argc and
argv. Out of these, argv is an array of pointers to strings and argc is an int whose value
is equal to the number of strings to which argv points. When the program is executed, the
strings on the command line are stored in memory and address of the first string is stored
in argv[0], address of the second string is stored in argv[1] and so on. The argument
argc is set to the number of strings given on the command line.
For example, consider a program which copy the contents of one file to another file.
Instead of the program prompting us to enter the source and target filenames, we must be
able to supply them at command prompt, in the form: filecopy PR1.C PR2.C
where, PR1.C is the source filename and PR2.C is the target filename.
if at the command prompt we give, filecopy PR1.C PR2.C then, argc would contain 3
argv[0] would contain base address of the string “filecopy”
15
16
16