You are on page 1of 82

Introduction to Functions

by
Dr. Subodh Srivastava
CSE,IIT (BHU)

Functions:
A function groups a number of program statements into a
single unit and give it names.
Every c program a collection of functions.
The function main() is executed first and it calls the other
functions directly or indirectly.
Every C program must have the function main().
We may have user defined functions which can be
called(invoked) from other parts of the program.
Monolethic program (a large single list of instructions)
becomes difficult to understand , debug ,test, and maintain.
A function has a clearly defined objective(purpose) and a
clearly defined interface with other functions in the
program.

It helps , reduction in program size.


Any sequence of statements that is
repeated in a program can be
combined together to form a function.
The function code is stored in only
one place in memory ,even though
it may be executed as many times as
user needs thus saving both time and
space

Functions are building blocks where every


program activity occurs.
They are self contained program segments that
carry out some specific, well defined task.
Every C program must have a function. One of
the functions must be main().
Additional functions will be subordinate to main()
and also to one another.

Functions
Functions
Modularize a program
All variables declared inside functions are local variables
Known only in function defined
Parameters
Communicate information between functions
Local variables
Benefits of functions
Divide and conquer
Manageable program development
Software reusability
Use existing functions as building blocks for new
programs
Abstraction - hide internal details (library functions)
Avoid code repetition

Divide and conquer


Construct a program from smaller pieces
or components
These smaller pieces are called modules

Each piece more manageable than the


original program

C functions can be classified into


two categories.
Library function: Predefined in the
standard library of C. Need is just to
include the Library.
User defined functions: They have
to be developed by the user at the
time of program writing.

Structure of C Functions:
Single Level Functions
#include<stdio.h>
main()
{
clrscr();/*clear the screen*/
printf(Welcome to the world of C programming\n);
printf(Programming is nothing but logic impletion);
The output of the Program will be:
Welcome to the world of C programming
Programming is nothing but logic impletion

Multiple Level Functions:

Showing functions at multiple level-one being invoked (called) by


another.
#include<stdio.h>
main()
{
void display_message();
/*function prototype or
declaration*/
clrscr();
display_message();
/*function call*/
getch(); /* freeze the monitor*/
}
/* function definition display_message()*/
void display_message()
{
printf(Welcome to the world of C programming\n);
printf(Programming is nothing but logic impletion);
}

The output of Program will be:


Welcome to the world of C programming
Programming is nothing but logic impletion

function display_meesage() is invoked from


main().

The function main(), which invokes the


function display_message(), is the calling
function,

and the function display_message() is the


called function.
The () can be used for passing values to functions,
depending on whether the receiving function is
expecting any parameter(argument).

An executable statement is
terminated by a semicolon(;).
A statement calling/executing a
function needs to be terminated by a
semicolon.
But, a statement marking the
beginning of a function-definition
does not have a semicolon at the end.
Note that main() may be called like
any other function.

Defining and Using Functions:


In C, function returns an int value by default i.e.,
when no type has been specified before the
function name it will always return an int value.
Function Prototype:
Like any variable in a C program, it is necessary to
prototype or declare a function before its use.
If it returns a value other than an int. It
informs the function would be referenced at
later stage in program .
The general form of function prototype is:

data type function_name (argument list);

The declaration of all functions statement should be first


statement in main().
The general form of function declaration using ANSI
prototype is :
data_type function_name(type1 arg 1,type2 arg 2.);
Where arg1,arg2.are the list of arguments.
For Example,
In previous program , the statement

void display_message(); is a function protoype or


declaration. Here void specifies that this function does not
return any value.

The empty parenthesis indicates that it takes no


parameters(arguments).

Function prototype
Function name
Parameters what the function takes in
Return type data type function returns (default int)
Used to validate functions
Prototype only needed if function definition comes after
use in program
The function with the prototype
int maximum( int, int, int );
Takes in 3 ints
Returns an int
Promotion rules and conversions
Converting to lower types can lead to errors

When we place the function prototype above all the


functions(including main()), it is know as global
prototype.

A prototype declared in global environment is available for


all the functions in the program.

When we palce the function prototype inside the definition


of another function(i.e., in the local declaration section),the
prototype is known as a local prototype.

Note: The function prototype is always terminated with a


semicolon.

Function prototypes are desirable because:

They facilitate error checking between calls to


a function and corresponding function definition .
They also help the compiler to perform
automatic type conversions on function
parameters.
When a function is called , actual arguments are
automatically converted to the types in
function definition using normal rules of
assignment.

Function Definition :
In C, a function must be defined prior to its use in the program.

the function definition contains the code for function.


The general form of a function definition is
data_type function _name(formal argument list)
argument declarations;
{
local variable declaration;
executable statement 2;

..
executablen;
return(expression);
}

Here, the type specifies the type of the value to be returned by


the function.
It may be any valid C data type.

When no type is given, the complier returns an integer value


Here, function_name is valid C identifier (no reserved word
allowed) defined by the user and it can be used by other
functions for calling this function.
The argument list is a comma-separated list of variables of a
function, enclosed within parentheses ,
through which the function may receive data or send data
when called from other function.
These are know as Formal or Dummy arguments.
Local variables are defined and used within the body of the
function.

Such variables are automatic local


variables as they are automatically
created each time the function is
called.
Body of the function enclosed within
the brace {.} is know as block.(The
difference between a block and
compound statement is that the
block has its own declaration
whereas the compound statement
does not.)

Calling or Invoking or Accessing


Functions
A function can be called(i.e., invoked) by specifying its name , followed
by a list of arguments enclosed in parentheses and separated by
commas.
The function call may appear by itself, or it may be one of the operands
within an expression (in case it returns a value).
The arguments or parameters appearing in the function call
are known as actual arguments, in contrast to formal
arguments that appear in the first line of the function
definition.
In a normal function call, there will be one actual arguments
for each formal arguments.
The actual arguments may be expressed as constants, single
variables or more complex expressions.
However, actual arguments must match in number, type and
order with their corresponding formal arguments.
If a function call does not require any arguments, an empty pair of
parenthesis must follow the function name.

Calling Convention:
It specifies the order in which
arguments(parameters) are passed when a
function is called. There are two possibilities:
(i) Parameters might be passed from left to right.
(ii) Parameters might be passed from right to
left .
C languages obeys the second order.
In C programs, function that have parameters are
called in one of the two ways:
Call by value
Call by reference

Calling Functions: Call by Value and Call


by Reference

Used when invoking functions


Call by value
Copy of argument passed to function
Changes in function do not effect original
Use when function does not need to modify argument
Avoids accidental changes
Call by reference
Passes original argument
Changes in function effect original
Only used with trusted functions
For now, we focus on call by value

Passing Parameters to Functions:


Call by value : Call by value means sending the

values of the arguments to functions .


When a single value is passed to a function via
an actual argument ,
The value of the actual argument is copied into
the function.
Therefore, the value of the corresponding
formal argument can be altered within the
function, but the value of the actual argument
within the calling routine will not change.
This procedure for passing the value of an
argument to a function is know as passing by
value or call by value.

Call by value :

/* find largest of three numbers using function*/


#include<stdio.h>
main()
{
void max (int x , int y , int z); /* function prototype */
int a,b,c;
clrscr();
printf(Enter the three numbers\n);
scanf(%d%d%d, &a, &b, &c);
/*echo the data*/
printf (\na=%8d b=%8d c=%8d, a,b,c);

/*function call call by value methods*/


max(a,b,c); /* a,b,c are actual parameters or arguments*/
/* function definition max ()*/
void max(intx, int y, int z) /*x,y,z are formal parameters*/
int big; /* local variables declaration */

big=x;
if(y>big)
big =y
if(z>big)
big=z;
printf(\n\nLagest of three numbers is %d\n,big);

}
The output of Program will be:
Enter the three numbers
60 75 40
a=
60
b=
75
c=
40
x=
60
y=
75
z=
40
Largest of three numbers is 75.
In the above program, value entered for variable a,b and
c in the main() function are passed to function
max().The values get copied into memory locations of the
arguments x,y,z respectively of the function max() when it is
called.

Below:
Content of a ,b,c
actual60arguments
75

60

40

75

x
formal arguments

40

void max (int x, inty , int z );


/* function prototype*/
void
type
Formal parameters
x, y,and z

Function max() call statement


max(a,b,c); /* a,b,c are actual parameters or arguments */
and the function max() definition,
void max(intx,inty,intz ) No semicolon here /* x,y,Z are formal
parameters*/
{
body of the function
}
No semicolon here.

E.g.: /* A simple C program containing a function that


alters the value of its argument */
#include<stdio.h>
main()
{

int a =2;

printf(\na =%d(from main,before calling the function),a);

modify(a);

printf(\na=%d ( from main, after calling the function),a);

modify (int a)

a*=3;

printf(\na=%d ( from the function, after being modified),a);

return;

O/P: a=2 (from main,before calling the function)


a= 6(from the function , after being modified )
a=2(from main, after calling the function)
The original value of a (i.e.=2) is displayed when main is executed.
This value is then passed to the function modify,
Where it is multiplied by three and the new value of the formal
argument that is displayed within the function.
Finally, the value of a within (i.e ., the actual argument) is
again displayed, after control is transferred back to function
main from function modify.
These result show that a is not altered within main,even
though the corresponding value of a is changed within modify.
Passing an argument by value has certain advantage and
disadvantages.
On the positive side,it allows a single valued actual argument
to be written as an expression rather than being restricted to
a single variable.

/*find the sum of the digits of a given number using function */


# include<stdio.h>
main()

int sumdigit(long int n); /* function prototype*/

long int num;

int sum;

clrscr();

printf(Enter the number\n\n);

scanf(%ld,&num);

sum=sumdigit(num); /* function call */

printf(\n\nSum of digits of %ld is %d\n,num,sum);

}
/* function definition sumdigit() */

int sumdigit(long int n)

int r,s=0;
/* local variables */

do
{
r=n%10;
s+=r; /* sum=sum+r */
n/=10 /* n=n/10 */
} while(n!=0)
return(s);
}

The output of the program will be:


Enter the number
45321
Sum of digits of 45321 is 15

/*leap year checking using a function */


# include<stdio.h>
main()
{
char leap(int yr), flag/*function prototype */
int year;
clrscr();
printf(Enter the year\n);
scanf(%d,&year);
flag=leap(year); /*function call */
if(flag==t)
printf(\n\n%d is a leap year\n,year);
else
printf(\n\n%d is not a leap year\n,year);
}

/*function definition leap()*/


char leap (int yr)
{
if((year%4==0)&& (year%100!=0) ||(year==0))
return(t);
else
return(f)
}
The output of the above program will be:
Enter the year
2007
2007 is not a leap year
Enter the year
2008
2008 is a leap year

The Return Statement:


Information returned from the function to the
calling portion of the program via return statement.
It causes control to be returned to the point from where
the function was accessed.
The return statement can take one of the following forms:
return;

or
return(expression);
In the return(expression );statement, the value of the
expression is returned to the calling of the program.
When return is used without parentheses , no value
is returned to the calling a function. When no return
is specified the function returns an integer value.

Result of computation by a function may be


returned to the calling program via statement.
Its syntax is:
return;
Or return (expression);
return is statement within the body of the function.
This forces a function to return immediately to the
function that is called it.
The returned value can be any except an array
or function.
. The arrays are retuned via pointers.
The type of value returned by the return statement
should match the type of the function.
Invoked function always returns a value unless it is declared as
void.
A function can have more than one return statement.

/* find largest of three numbers using function*/


#include<stdio.h>
main()
{
int max (int x , int y , int z); /* function prototype */
int a,b,c,result;
/* int a,b,c; */
clrscr();
printf(Enter the three numbers\n);
scanf(%d%d%d, &a, &b, &c);
/*echo the data*/
printf (\na=%8d b=%8d c=%8d, a,b,c);

/*function call call by value methods*/


result= max(a,b,c); /* a,b,c are actual parameters or arguments*/
printf(\n\nLagest of three numbers is %d\n,result);
}
/* function definition max ()*/
int max(intx, int y, int z) /*x,y,z are formal parameters*/
int big; /* local variables declaration */

big=x;
if(y>big)
big =y
if(z>big)
big=z;
return(big);

}
The output of Program will be:
Enter the three numbers
60 75 40
a=
60
b=
75
c=
40
Largest of three numbers is 75.
Always remember that a returns statement always
return one value. When return is used without
parentheses , no value is returned to the calling a
function. When no return is specified the function
returns an integer value.
A function can have more than one return statement.

Note: We can code the program without using


the variable result by making the following
change in it.
Change the statement, int a,b,c,result; in main()
inta,b,c;

and the last two statement of main(),i.e.,

result=max(a,b,c) / \n\nLargest of three


numbers is %d\n,result);
Being replaced by a single statement,

printf(\n\nLargest of three numbers is


%d\n,max(a,b,c));

Category of Functions:
In C, the functions can be divided
into the following categories:
(i) Function with no arguments and
no returns values.
(ii) Function having arguments but no
return values.
(iii) Function having arguments and
retuns values also.

(i) Function with no Arguments and


no return values.(No data exchange
takes place in any direction)
When a function is without arguments ,it does not
receive any data from the calling function nor does the
calling function get any data from the called function .
So, we can say that no data exchange takes place in
any direction .
Such type of function function can not be used in any
expression and it always coded as a standalone
statement.
For example , the declaration

void display(void)
{

printf(Always enjoy your life\n);


}
For calling this function we use
display();

(ii) Function having arguments but


no return values:
There are situation when the calling function sends the
data to the called function after validating it .
/* simulate calculator using a function */
main()

void calc(float val1,float val12,char op);/*function


prototype */

float num1,num2;

char operator;

clrscr();

printf(\n Enter two numbers\n);

scanf(%f%f,&num1,&num2);

fflush(stdin);/* Clear the buffer*/

printf(\nEnter an operator out of (+ - * /)\n);


scanf(%c,&operator );

calc( num1,num2,operator); /*function call */


}
/*function definition calc()*/
void calc (float val1, float val12, char op)
{
printf(\n);
switch(op)
{
case +:
printf(Result is %8.2f,val11+val12);
break;
case -:
printf(Result is %8.2f,val1-val12);
case *:
printf(Result is %8.2f,val1*val12);

case /:

if(val12 !=0)

printf(Result is 8.2f,val1/val12);

break;

default:

printf(\n invalid operator\n);

break;

}
}
The output of Program will be:

Enter two numbers

50 20

Enter an operator out of (+ - * /)

Result is 1000.00

Enter two numbers


40 25
Enter an operator out of (+ - * /)
/
Result is 1.60
Enter two numbers
45 0
Enter an operator out of (+ - * /)
/
Division by zero not possible

(iii) Function having Arguments


and Return values also:
Sometimes, we may require that the
result from the called function is
needed by the calling function for
further use.
Such type of function assures a high
degree of portability between
programs as it provides a two way
communication between the
calling and the called functions.

/*Program to compute a function f(x) defined as


f(x)=-3 if x<-3
=x if -3<=x<=3
=3 if x>3
*/
#include<stdio.h>
main()
{
int f(int x); /* function prototype */
int x;
clrrscr ();
printf(Enter an integer\n\n);
scanf(%d,&x);
printf(\nf(%d)=%d\n,x,f(x)); /* function call */
getch();/*freeze the monitor */
}

/* function definition f() */


int f(int x )
{
if(x<-3)
return(-3)
if (x>=-3&& x<=3)
return(x);
else
return(3);
}
The output of program will be:
Enter an integer
-50
F(-50)
=-3

Enter an integer
0
f(0)=o
Enter an integer
7
f(7)=3

Returning Non-integer value from


Functions:
A function in C returns an int type value by default.
There are situations when int type data does not
serve the purpose and char , float or double
type data must be returned to the calling
function.
In such cases the type of data received by
the calling function and the called function
must be same.

/* add three numbers using function */


#include<stdio.h>
main()
{
float add(float,float,float); /* function prototype */
float a,b,c,sum;
clrscr();
printf(Enter three numbers for addition\n\n);
scanf(%f%f%f, &a,&b,&c);
sum=add(a,b,c) /*function call*/
printf(\n\nSum of three numbers is % 8.2f\n\n,sum);
getch(); /*freeze the monitor */
}
/*function definition add() */
/* through a,b,c are also in main but formal parameters
a,b,c used in add() are different from these*/
float add (float a,float b, float c)
{
return (a+b+c);

The output of program will be:


Enter three numbers for addition
20.5 32.8 55.3
Sum of three numbers is 108.60

Nesting of Functions:
In C, the nesting of functions is allowed. It does not mean that
a function can be defined inside another function but by
nesting we mean calling of a function by another
function , which in turn call another function and so on.
There is no limitation on nesting of function in C.
For example, main() can call function func1(),which calls
function func2(),which calls function func3() and so on.
/* illustration of nesting of functions */

#include<stdio.h>

main()

clrscr();

printf(Hello Students!);

func1();/* function call */

/* function definition func1()*/


func1()
{
printf(\n God Helps);
func2();/*function call*/
}
/* function definition func2()*/
func2()
{
printf(THOSE WHO);
func3();/*function call*/
}
/* function definition func3()*/
func3()
{
printf(HELP THEMSELVES\n);

The output of Program 10 will be:


Hello Students
GOD HELPS THOSE WHO HELP
THENSELVES

Recursion in Function:
Recursion is a process by which a function calls
itself repeatedly,until some specified condition has
been satisfied.
The process is used for repetitive computation in
which each action is stated in terms of previous
result.
In C, a function can call itself, this is called recursion. A
function is said to be recursive if there exists a statement
in its body for the function call itself.
Recursion is sometimes called circular definition.
The main advantage of recursion is that it is useful writing
clear,short and simple programs.

Recursion is implemented using C


language , by defining a function in
terms of itself,i.e.,
function invoke itself.
A commonly used example, finding the
factorial of a number.
The factorial of a number n (denoted
as n!) is defined as:
n!=nx(n-1)x(n-2)x.1
which can be expressed as:

n!=nx(n-1)!

A recursive definition wherein the factorial of a


number is defined in terms of itself, i.e., the
factorial n! is defined in terms of itself of
factorial (n-1)!
Obviously, this recursive definition should have a
stopping condition, otherwise an infinite loop will
result.
In this case
0!=1
Thus, the complete definition of the factorial
function is:

n!=n x(n-1)! With 0!=1

/* Find factorial of a number using a non-recursive function*/

#include<stdio.h>

main()

long int factorial(int n); /* function prototype */

int n;

clrscr();

printf(Enter the number for finding factorial:);

scanf(%d,&n);

if(n<0)

printf(\n Factorial of % d not defined\n,n);

else

printf(\n Factorial of %d =%ld, n, factorial(n));


/*factorial call */

/* function definition factorial */


long int factorial (int n)
{
int i; /*local variable */
long int prod=1
for(i=1; i<=n;i++)
prod=prod*i;
return(prod);
}

The output of Program will be:


Enter the number for finding factorial:10
Factorial of 10=3628800
Enter the number for finding factorial:-7

/*find factorial of a number recursively */

#include<stdio.h>

main()

long int factorial(int n);/* function prototype*/

int n;

clrscr();

printf(Enter the number for finding factorial:);

sacnf(%d,&n);

if(n<0)

printf(\nFactorial of %d not defined\n,n);

else

printf(\nFactorial of %d=%ld,n, factorial (n));/*


function call*/

/*recursive function definition factorial() */


long int factorial (int n)
{
if(n==0)
return(1);
else
return(n*factorial (n-1));
}
The Output of Program will be:
Enter the number for finding factorial:4
Factorial of 4=24

Working of Recursion:
During each of a recursive function, a different set of local variables
is created. The names of these local variables are same , but all of
them are different .
They store different set of values during each call of the
subprogram.
The fibonacci terms are 0,1,1,2,3,5,8,.In this sequence each
term(except the first two )are obtained by adding its two immediate
predecessor terms. The recursive definition of this sequence is:

fib(n) = { 0 if n=1

1 if n=2

fib(n-1)+fib(n-2) if n>2
While coding recursive function , we must take care that there
exists a reachable termination inside the function so that
function may not be invoked endlessly.

/*Generate first n fibonacci terms using recursion*/


#include<stdio.h>
main()
{
int n,i;
long fib(int n); /* function prototype*/
clrscr();
printf(\n How many fibonacci terms you want to
generate?\n);
scanf(%d,&n);
printf(\nFirst %d fibonacci terms are\n\n,n);
for(i=1;i<n;i++)
{
printf(%ld\t,fib(i)); /*function call fib() */
}

/*function definition fib() */


long fib(int n)
{
if(n==1)
return 0;
else
{
if(n==2)
return 1;
else
return(fib(n-1)+fib(n-2));
}
}
The output of Program will be:
How many fibonacci terms you want to generate?
20

First 20 fibonacci terms are


0
1 1 2 3 4 5 8 13 21 34 55 89 144 233
377 610 987 1597 2584 4181

Recursion vs. Iteration


Repetition
Iteration: explicit loop
Recursion: repeated function calls

Termination
Iteration: loop condition fails
Recursion: base case recognized

Both can have infinite loops


Balance
Choice between performance (iteration) and
good software engineering (recursion)

Make Your Own Header File

Step1 : Type this Code


int add(int a,int b)
{
return(a+b);
}
In this Code write only function definition as you write in
General C Program.

Step 2 : Save Code


SaveAbove Code with[.h ] Extension.
Let name of our header file bemyhead[ myhead.h ]
Compile Code if required.

Step 3 : Write Main Program

#include<stdio.h>
#include"myhead.h"

void main()
{
int num1 = 10, num2 = 10, num3;
num3 = add(num1, num2);
printf("Addition of Two numbers : %d", num3);
}
Include Our New Header File.
Instead of writing< myhead.h>use this
terminologymyhead.h
All the Functions defined in themyhead.h headerfile are now
ready for use .
Directly call function add(); [ Provide proper parameter and
take care of return type ]

Note
While running your program
precaution to be taken : Both files
[myhead.h and sample.c] should
be in same folder.

Data Storage Types in C:


Data storage determine about the storage of a variable. Its syntax
is:

storage-specifier type variable_ name;


There are four storage class specifiers in C:
A) auto
B) register
C) static
D) extern
A variable in C is completely defined with the above specification .
A variable can be stored either in the memory or the CPU
registers.
So, to completely know about the variables where about
i.e.,
(1) Storage place
(2) Default initial value
(3) Scope
(4)Lifetime
A storage-specifier is needed.

A) auto
A variable is declared automatic as given

auto type variable_name;


By default, all the variables are auto unless
we specify some other storage specifier. So
with an auto storage-specifier a variable
has:
1) Storage place: Memory
2) Default initial value: Garbage value
3) Scope: Local to the function(or internal)
4)Life time: Till the parent function is executing.

/*illustration of auto variables*/


#include<stdio.h>
main()
{
auto int x=1024;
clrscr();
func1();/*function call */
printf(\n%d\n,x);
getch();/* freeze the monitor*/
}
/*function definition func1()*/
func1()
{
auto float x=50.0;
func2();/*function call*/
printf(\n%8.2f\n,x);
}

/* function definition func2()*/


func2()

auto char x=A;

printf (\n%c\n,x);

}
The o/p of program will be:
A
50.00
1024

B) register
A variable is declared as given given below:
register type variable_name;
All the variable can not be defined of registers storage
type for two reasons:
A) Limited number of CPU registers(14 in a PC usually).
B) Size of the CPU registers(16 bits a PC usually).
But a register variable provides a fast access than those in
memory. So, the time taken to read a variable from memory
is saved in this case. A variable with a register storage
specifier has
1) Storage place: CPU registers (if possible)
2) Default initial value: Grabage vale
3) Scope: Local to the function
4) Life time: Till the parent function is executing.

Note*: The register variables are automatically converted


to non-register variables if either the register of CPU are
already full or the variable does not fit on the CPU register.
C) Static:
There are static local and static global variables. A variables is
declared static as given below:

static type variable_name;


A static global variable is available for entire time in which it is
declared . From other files of the program, it is hidden.
A static local variable is initialized only once when the function is
called first time(in which it is declared).
It holds (retains) its value even when the control leaves the
function and the value last time around will be used when
the control enters next time in the function.

It can be accessed only with the


function in which it is declared but
has the life time of a global variables.
A variable with a static storage
specifier has:
Storage place: Memory
Default initial value : 0
Scope: Local to the function or file
scope
Life time: Entire program execution.

/*illustration of a static variable*/


#include<stdio.h>
main
{
int i;
clrscr();
for(i=1;i<4;i++)
func(); /*function call */
}
/* function definition func1() */
func1()
{
static int =3; /* num declared static */
printf(%d\n\n,num*num);
num++;
}
The output of Program will be:
9
16
25
36 Here the function func1() is called four times from main().During first call
the value of num is 3 and when the function func1() it becomes 4. The same
value i.e.,4 is used during the second call and num is incremented to 5 and
so on.

In summary, we can say that the value of a static variable persists


between different calls to the same function.

D) extern
A variable is declared extern as given below:

extern type variable_name;

When a program is divided into two or more files, then a


global variable should not be declared separately for each
file.
In this case the global variable is preceded by the keyword
extern.
It tells the compiler that the variable name after extern has been
declared somewhere else and no separate memory is allocated to
it.

A variable with an extern storage specifier


has:
A variable with an extern storage specifier has:
1) Storage place: Memory
2)Default initial value: 0(zero)
3) Scope: File scope
4) Life time: Entire program execution

/* illustration of global variables */


# include<stdio.h>
int value; /* global declaration */
main()
{
value=100; /*Value is global here*/
clrscr();
printf (value=%d\n,value);
printf (\nvalue=%d\n,func1());
printf (\nvalue=%d\n,func2());
printf (\nvalue=%d\n,func3());
printf (\nvalue=%d\n,func4());
getch(); /* freeze the monitor*/
}
/* function definition func1()*/
func1()
{
value *=2 /* value is global here*/
return(value);
}

/* function definition func2()*/


func2()
{
int value =500; /* value is local here*/
return(value);
}
/* function definition func3()*/
func3()
{
value *=5 /* value is global here*/
return(value);
}
/* function definition func4()*/
func4()
{
value /=100 /* value is global here*/
return(value);
}

The output of Program will be:


value=100
value=200
value=500
value=1000
value=10

Storage Class specifiers and Functions


In C, static and extern storage class specifier can be used
with functions.
Static Function:
When the keyword static is used before a function, it can be
accessed only in the file in which it is declared. This
function cannot be accessed outside its own file.
But, the same name can be used by some other file.
Extern Function:
It is similar to an extern variable . When the keyword
extern is used before a function, it means that this function
exists in some other file. For dividing a large program into
multiple files it is quite useful.

You might also like