3. LIBRARYFUNCTIONS
– Library functions are not required to be written by
us
– printf and scanf belong to the category of library
function
– sqrt, cos, strcat, etc aresome of library functions
4. USER-DEFINEDFUNCTIONS
– User-defined functions hasto be developed bythe
user at the time of writingaprogram
– Auser-defined functions can later become apart
of the Cprogramlibrary
– main is an example of user-definedfunctions
5. NEEDFORUSER-DEFINEDFUNCTIONS
•
•
Everyprogram must have amain function
It is possible to code any program utilizing only main
function, it leads toanumber of problems
The program may become too large and complex
and asa result the task of debugging, testing, and
maintaining becomes difficult
If a program is divided into functional parts, then
each part may be independently coded and later
combined into asingleunit
These subprograms called ‘functions’ are much
easier to understand, debug, andtest
•
•
•
6. NEEDFORUSER-DEFINEDFUNCTIONS
•
•
•
• There are times when some types of operation or
calculation is repeated at many points throughouta
program
In such situations, we may repeat theprogram
statements whenever they areneeded
Another approach is to design afunction thatcan be
called and used whenever required
Thissavesboth time andspace
7. NEEDFORUSER-DEFINEDFUNCTIONS
• Thissub-sectioning approach clearly results in a
number of advantages
– It facilitates top-down modularprogramming.
– Thelength of asource program can be reduced by using
functions at appropriate places. Thisfactor isparticularly
critical with microcomputers where memory spaceis
limited
– It is easy to locate and isolate afaulty function for further
investigations
– Afunction may be used by many other programs, this
means that aCprogram can build on what othershave
already done, instead ofstarting over, from scratch.
8. AMULTI-FUNCTION PROGRAM
•
•
Afunction is aself-contained block of codethat
performs aparticular task
Onceafunction hasbeen designed and packed, it can
be treated asa‘black box’ that takes some datafrom
the main program and returns avalue
The inner details are invisible to the rest of the program
Example:
main()
{
printline();
printf("This illustrated the useof Cfunctionsn");
printline();
}
printline()
{
int i;
for(i=1; i<40; i++)
pintf("-");
printf("n");
}
•
•
9. ELEMENTSOFUSER-DEFINED
FUNCTIONS
•
•
Functions are classified asone of the derived data types inC
Candefine functions and usethem like any other variablesin
Cprograms.
Similarities between functions and variables inC
– Both function name and variable namesare considered
identifiers and therefore they must adhere to the rules for
identifiers.
– Likevariables, functions have types (such asint) associated with
them
– Likevariables, function names and their types must bedeclared
and defined before they are used inaprogram
•
10. ELEMENTSOFUSER-DEFINED
FUNCTIONS
• There are three elements related to functions
– Function definition
– Function call
– Function declaration
Thefunctiondefinition is an independent program module
that is specially written to implement the requirements of the
function
Touse this function we need to invoke it at arequired place
in the program. Thisis known asthe functioncall.
Theprogram that calls the function is referred toasthe
callingprogram or calling function.
Thecalling program should declare any function that is tobe
used later in the program. Thisis known asthe function
declaration or functionprototype.
•
•
•
•
12. DEFINITIONOFFUNCTIONS
• Afunction definition, also known asfunction
implementation shall include the followingelements;
– Function name;
– Function type;
– List of parameters;
– Local variable declaration;
– Function statements; and
– Areturn statement.
All six elements are grouped into twoparts, namely,
– Function header (First three elements);and
– Function body (Second three elements)
•
13. THEFORMOFCFUNCTION
function_type function_name(parameter list)
{
local variable declaration;
executable statement1;
executable statement2;
return(expression);
}
Thefirst line function_type function_name(parameterlist) is
known asthe function header.
Thestatements within the opening and the closingbrace
constitute the functionbody.
•
•
14. FUNCTIONDEFINITION
• Function Header
– Thefunction header consists of three parts: the function type (also
known asreturn type), the function name and formal parameterlist.
– Semicolon is not used at the end of the function header
Name and Type
– The function type specifies the type of value (like float or double) that
the function id expected to return to the program calling the function
– If the return type is not explicitly specified, Cassumeit asan integer
type.
– If the function is not returning anything then we need to specify the
return type asvoid
– Thefunction name is any valid Cidentifier and therefore ,just follow
the samerules of formation asother variable namesinC
•
15. FORMALPARAMETERLIST
• The parameter list declares the variables that will receive the
data sent by the callingprogram.
They serve asinput data to the function to carry out the
specified task.
Theyrepresent actual input values, they are often referredto
asformal parameters.
Theseparameters can also be used to send values to the
calling programs
Theparameter is known asarguments.
– float quadratic (int a, int b, intc) { …..}
– double power (double x, int n) {…..}
– int sum(int a, int b) { …..}
There is no semicolon after the closingparenthesis
Thedeclaration parameter variables cannot becombined
•
•
•
•
•
•
16. FORMALPARAMETERLIST
• Toindicate that the parameter list is empty,we usethe
keyword void between the parentheses asin
void printline (void)
{
…
}
Many compiler accept an empty set ofparentheses
void printline()
It is good to use void to indicate a nill parameter list
•
•
17. FUNCTIONBODY
• Thefunction body contains the declarations andstatements
necessary for performing the required task. Thebody
enclosed in braces, contains threeparts,
– Localdeclarations that specify the variables needed by thefunction
– Function statements that perform the task of the function
– Areturn statement that returns the value evaluated by thefunction
If afunction does not return any value, we can omit the
return statement.
Its return type should be specified asvoid
•
•
18. RETURNVALUESANDTHEIRTYPES
•
•
•
•
• Afunction may or may not send back any valueto
the callingfunction
Done through return statement
It is possible to send any number of values to the
called function
Thecalled function can only return one value percall
SYNTAX:
return;
or
return (expression);
19. RETURNVALUESANDTHEIRTYPES
•
•
• return;
– Plain return does not return anyvalue
– Acts asthe closing brace of thefunction
– Thecontrol is immediately passedback to the callingfunction
– EXAMPLE:
if(error)
return;
return (expression);
– Return the value of theexpression
EXAMPLE:
mul(x,y)
int x,y;
{
int p;
p =x*y;
return(p);
}
– Returns the value of p which is the product of the values of x and y
– Thelast statement can be combined into one statement
as return(x*y);
20. RETURNVALUESANDTHEIRTYPES
•
•
•
Afunction may have more than one returnstatements
Thissituation arises when the value returned isbased
on certain conditions
EXAMPLE:
if(x <=0)
return(0);
else
return(1);
Return type of data:
– All function by default return int type data
– We can force afunction to return aparticular type ofdata
by using type specifier in the functionheader
– EXAMPLE:
double product(x,y)
float sqr_root(p)
– When avalue is returned, it is automatically cast tothe
function’s type
•
21. CALLINGAFUNCTION
• Afunction canbe called by simply using the function
name in astatement
• When the function encounters afunction call,the
control is transferred tothe function mul(x,y)
main()
{
int p;
p =mul(10,5);
printf("%dn", p);
}
int mul(int x,inty)
{
int p; /*local variables*/
p =x* y;/* x=10, y =5*/
return(p);
}
22. CALLINGAFUNCTION
• Thefunction is executed and the value isreturned
and assigned to p
Afunction which returns avalue can be used in
expressions like any other variables
printf("%dn", mul(p,q));
y =mul(p,q) / (p+q);
if (mul(m,n)>total)
printf("large");
Afunction cannot be used on the right side ofan
assignment statement
mul(a,b) =15;
Afunction that does not return any value may notbe
used in expression; but can be called to perform
certain tasks specified in thefunction
main() { printline();}
•
•
•
23. FUNCTIONDECLARATION
• Afunction declaration consists of fourparts
– Function type (return type)
– Function name
– Parameter list
– Terminating semicolon
Format
– Function-type function-name (parameterlist);
Very similar tothe function header line expect the
terminating semicolon.
– int mul(int m, int n); /* Function prototype */
Equally acceptable forms of declarationsare
– int mul (int,int);
– mul (int a, intb);
– mul (int, int);
•
•
•
24. FUNCTIONDECLARATION
• When afunction does not take any parameters and doesnot
return any value, its prototype is writtenas:
void display (void);
Aprototype declaration may be placed in two places ina
program.
– Above all the functions (including main) (globalprototype)
– Inside afunction definition (localprototype)
It is good to declare prototypes in the global declaration
section before main.
It adds flexibility, provides an excellent quick reference to the
functions used in the program, and enhancesdocumentation
•
•
•
25. CATEGORYOFFUNCTIONS
• Category 1: Functions with no arguments andno
return values
Category 2: Functions with arguments and noreturn
values
Category 3: Functions with arguments andone
return values
Category 4: Functions with no arguments butreturn
avalue
Category 5: Functions that return multiplevalues
•
•
•
•
26. NOARGUMENTSANDNORETURN
VALUES
•
•
•
• When afunction hasno arguments, it doesnot
receive any data from the callingfunction
When itdoes not return avalue, the calling function
does not receive any data from thecalled function
There is no data transfer between thecalling
function and the calledfunction
There is only a transfer of control but not data
29. ARGUMENTSBUTNORETURN
VALUES
• Thecalling function read data fromthe terminal and
passit on to thecalled function.
It is aoneway data communication,i.e. the called
program receives data from calling program but it
does not return any value tothe calling program.
Thisapproach is wiser becausethe calling function
can check for the validity of data, if necessary, before
itis handed over to the called function.
Called function with arguments
value(p,r,n)
•
•
•
30. ARGUMENTSBUTNORETURN
VALUES
• Thefunction call
value(500,0.12,5)
Would send the value 500, 0.12, 5 to thefunction
value(float p, float r, intn)
and assign500 to p, 0.12 to r and 5 to n
Thevalues 500, 0.12, 5 are the actualarguments
Thearguments p, r, n are the formalarguments
Theactual and formal arguments should matchin
number, type, andorder
Thevalues of actual arguments are assigned to the
formal arguments on aone to onebasis
•
•
•
•
•
•
31.
32.
33. ARGUMENTSBUTNORETURN
VALUES
• if the actual arguments are more than the formal
arguments, the extra actual arguments arediscarded
If the actual arguments are lessthan the formal
arguments, the unmatched formal argumentsare
initialized to some garbagevalues
No error messagewill begenerated
Theformal arguments must be valid variablenames
Theactual arguments my be variable names,
expression, or constants
When afunction call is made, only acopy of the
values of actual arguments is passedinto thecalled
function
•
•
•
•
•
34. EXAMPLE
#include <stdio.h>
#include<conio.h>
add(int, int);
void main()
{
int a,b;
printf("nEnter two number:");
scanf("%d%d",&a,&b);
add(a,b);
}
}
add(int x, int y)
//function with arguments
{
int z;
z=x+y;
printf("nSum is:%d",z);
OUTPUT
:
Enter two number:2
4
Sumis:6
35. ARGUMENTSWITHRETURNVALUES
•
•
• Here data transfer take place between the calling
function and the called function aswell asbetween
called function and calling function.
It is a two way data communication, i.e. the called
program receives data from calling program and it
return some value to thecalling program.
Aself-contained and independent function should
behave like a‘black box’ that receives apredefined
form of input and outputsadesired value
36.
37. EXAMPLE
#include <stdio.h>
#include<conio.h>
add(int, int);
void main()
{
int a,b;
float c;
printf("nEnter two number:");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("nSum is:%f",c);
}
add(int x, int y)
{
float z;
z=x+y/3;
return(z);
}
OUTPUT
:
Enter two number:6
7
Sumis:13
38. RETURNINGFLOATVALUE
• Cfunction returns avalue of the type int asadefault
casewhen no other type is specifiedexplicitly.
return(z);
Return the integer value ofsum
This is due to the absence of the type-specifier in the
function header
There will be times when we may find it necessary to
receive the float or double type of data
We must explicitly specify the return type on both
the function definition and the prototypedeclaration
•
•
•
•
39. EXAMPLE
#include <stdio.h>
#include<conio.h>
float add(int, int);
void main()
{
int a,b;
float c;
printf("nEnter two number:");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("nSum is:%f",c);
}
float add(int x, inty)
{
float z;
z=x+y/3;
return(z);
}
OUTPUT
:
Enter two number:6
7
Sumis:13
40. RETURNINGNON-INTEGERVALUE
• The type-specifier tells the
compiler, the type of data
the function is toreturn
Thecalled function mustbe
declared at the start of the
body in the callingfunction,
like any other variable. This
is to tell thecalling function
the type of data that the
function is actually
returning
•
float mul(float, float);
double div(float, float);
main() {
float a,b;
a= 12.345;
b =9.82;
printf("%fn", mul(a,b));
printf("%fn", div(a,b));
}
float mul(float x,floaty)
{
return(x*y);
}
double dic(float p, floatq)
{
return(p/q);
}
41. NOARGUMENTSBUTRETURNSA
VALUE
• There could be
occasionswhere we
may need adesign
functions that may not
take any argumentsbut
returns avalue to the
calling function.
int get_number(void);
main()
{
int m =get_number();
printf(“%d”,m);
}
int get_number(void)
{
int number;
scanf(“%d”, &number);
return(number);
}
42. FUNCTIONSRETURNINGNOTHING
• Functions that do not return
any values are not declaredin
the main
main()
{
printline();
value();
printline();
}
printline()
{
....
}
value()
{
....
}
• We can also declare them in
the main with the qualifier
void
• Thisstates explicitly that the
functions do not return
values
main()
{
void printline();
void value();
void printline();
}
void printline()
{
....
}
void value()
{
....
}
43. FUNCTIONSTHATRETURN
MULTIPLEVALUES
•
•
Areturn statement can return only onevalue.
Toget more information from afunction, wecan
achieve this in Cusing the arguments not only to
receive information but also to send back
information to the callingfunction.
Thearguments that are used to “sendout”
information are called outputparameters.
Themechanism of sending back information through
arguments is achieved using what are known asthe
address operator (&) and indirection operator(*).
•
•
44. PROGRAM
void mathoperation(int x, int y, int *s, int *d);
main()
{
int x=20, y =10, s,d;
mathoperation(x,y,&s,&d);
printf("s=%dn d=%dm",s,d);
}
void mathoperation(int x, int y, int*sum, int
*diff)
{
*sum =a+b;
*diff =a-b;
}
•
•
•
xand y – input arguments
sand d – output arguments
We pass
– Valueof
– Valueof
xto a
y to b
– Addressof
– Addressof
sto sum
d to diff
• Thebody of the function
when executed add the
value and find difference
and store the result in
memory location pointed
by sumand diff.
45. FUNCTIONSTHATRETURN
MULTIPLEVALUES
• The indirection operator * indicates the variables are to store
addresses, not actual values of variables
Theoperator * is known asindirection operator because it gives
an indirect reference to avariable through itsaddress
Thevariables *sum and *diff are known aspointers andsum
and diff aspointer variables
They are declared asint, they can point to locations of int type
data
Theuseof pointer variables asactual parameters for
communicating data between functions is called “passby
pointers” or “call by address orreference”.
•
•
•
•
48. RECURSION
•
•
•
When acalled function in turncalls another function a
process of ‘chaining’occurs
Recursion is aspecial case,where afunction calls itself
EXAMPLE:
main()
{
printf("This is an example of recursionn");
main();
}
OUTPUT
:
This is an example of recursion
This is an example of recursion
This is an example of recursion
Thisis an exa
Execution is terminated abruptly
•
•
49. EXAMPLE
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
int factorial (int);
printf("nEnter the number:");
scanf("%d",&a);
printf("The factorial of %d!is
%d",a,factorial(a));
}
int factorial(int x)
{
int f;
if(x==1)
return(1);
else
f=x*factorial (x-1);
return(f);
}
OUTPUT
:
Enter the number:5
Thefactorial of 5! is120
50. FUNCTIONSWITH1DARRAYS
•
•
Possible to passthe values of an array toafunction
To pass an array to a called function, it is sufficient to
list the name of the array without any subscripts, and
the sizeof the array asarguments
The call:
largest(a,n);
will passall the elements contained in thearray aof
size n.
Thecalled function expecting this call mustbe
appropriately defined
Thelargest function headeris
float largest(float array[], intsize)
•
•
•
•
51. FUNCTIONSWITH1DARRAYS
• Thefunction header(largest) is defined to take two
arguments, the array name and the sizeof thearray
to specify the number of elements in the array
Thedeclaration of formal argument arrayis
float array[];
Thepair of brackets informs the compiler thatthe
arguments array is an array of numbers
It is not necessary to specify the size of the array
here
•
•
•
52. FUNCTIONSWITH1DARRAYS
• Here an array is transferred asparameter to a
function.
void fun(int b[], intn)
{
int x,b[5];
…
…
…
…
.
.
…
…
…
…
.
.
void main()
{
void fun(int[],int);
int a[5],n;
…
…
…
…
…
fun(a,n);
…
…
…
…
…
}
}
53. EXAMPLE
#include<stdio.h>
#include<conio.h>
void add(int[],int b);
void main()
{
int a[5],i,n;
clrscr();
printf("n Enter theNumber:
");
scanf("%d",&n);
printf("n Enter the Values:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
add(a,n);
}
void add(int b[],int x)
{
int sum=0,i;
for(i=0;i<x;i++)
sum=sum+b[i];
printf("nThe sum is:%d",sum);
}
OUTPUT
:
Enter the Number:5
Enter the Values: 1
2
3
4
5
Thesum is: 15
54. FUNCTIONSWITH2DARRAYS
• Canalso passmulti-dimensional arrays to functions.
Therules are:
– Thefunction must be called by passing only thearray
name
– In the function definition, we must indicate that the array
hastwo-dimensional by including two sets ofbrackets
– Thesizeof the second dimension must bespecified
– Theprototype declaration should be similar tothe
function header
55. PROGRAM
main()
{
int M=3,N=2;
float average(int [][N],int,
int);
float mean;
int matrix[M][N] ={{1,2},
{3,4}, {5,6} };
mean =average(matrix, M,
N);
}
float average(int x[][N], intM,int
N)
{
int i, j;
float sum =0.0;
for(i=0; i<M; i++)
for(j=0; j<N; j++)
sum+=x[i][j];
return(sum/(M*N));
}
56. PASSINGSTRINGSTOFUNCTIONS
• Thestrings are treated ascharacter arrays in Cand
therefore the rules for passing strings to function are
very similar to those for passingarrays to functions
Basicrules are
– Thestring to be passedmust be declared asaformal
argument of the function when it is defined
Example:
voiddisplay(char item_name[])
{
...
}
•
57. PASSINGSTRINGSTOFUNCTIONS
– Thefunction prototype must show that the argument is a
string
voiddispay(char str[]);
– Acall to the fuction must have astring arrayname without
subscripts asits actual argument
Example:
display(names);
Nameis aproperly declared string array in the callingfunction
Like arrays, strings in Ccannot be passedby value to
function
•
58. THESCOPE,VISIBILITYAND
LIFETIMEOFVARIABLES
• It is very important to understand the concept of
storage classesand their utility in order to develop
efficient multifunction programs
In Cthere are four storageclasses
– Automatic variables
– External variables
– Static variables
– Register variables
Here we discussthe scope, visibility and longevityof
the above classof variables
•
•
59. THESCOPEANDLIFETIMEOF
VARIABLESINFUNCITONS
• SCOPEOFVARIABLE
– Determines over what parts of the program a variable is actually
available for use(active)
LONGEVITY
– Refers to the period during whichavariable retains agiven value
during execution of program(alive)
– It has adirect effect on the utility of agiven variables
VISIBILITY
•
•
• The visibility refers to the accessibility of avariable from the
memory
• Variables are categorized depending on the place oftheir
declaration
– Internal (local)
• Internal variables are those which are declared within aparticular
function
– External (global)
• External variables are declared outside of anyfunction
60. AUTOMATICVARIABLES
• Automatic variables are declared inside afunction in
which they are to beutilized
Theyare created when the function is called and
destroyed automatically when the function isexited,
hence the nameautomatic
Automatic variables are therefore private tothe
function in which they aredeclared
Automatic variables are also referred to aslocalor
internal variables
•
•
•
61. AUTOMATICVARIABLES
• Avariable declared inside afunction without storage
classspecification is, by default, an automatic variable
Thestorage classof the variable number isautomatic
main()
{
int number;
.......
}
We may also usethe keyword auto to declareautomatic
variables explicitly
main()
{
auto int number;
.......
}
•
•
64. AUTOMATICVARIABLES
• There are two consequences of thescopeand
longevity of autovariables
Any variable local to main will normally live
throughout the whole program, although itis active
only in main.
During recursion, the nested variables areunique
auto variables
•
•
65. EXTERNALVARIABLES
• Variables that are both alive and activethroughout
the entire program are known asexternalvariables
Theyare also known asglobal variables
Global variables can be accessedby any function in
the program
External variables are declared outside afunction
•
•
•
66. EXTERNALVARIABLES
int number;
float length =7.5;
main)
{
.....
}
function1()
{
.....
}
function2()
{
.....
}
•
•
Thevariables number and length are available for usein allthe
three functions
In casealocal variables and aglobal variable have the same
name, the local variable will have precedence over theglobal one
in the function where itis declared
68. EXAMPLE
int fun1(void);
int fun2(void);
int fun3(void);
int x;
main()
{
x=10;
printf("x =%dn",x);
printf("x =%dn",fun1());
printf("x =%dn",fun2());
printf("x =%dn",fun3());
}
fun1(void)
{
x=x+10;
}
fun2(void)
{
int x
x=1;
return(x);
}
fun3(void)
{
x=x+ 10;
}
69. EXAMPLE
int fun1(void);
int fun2(void);
int fun3(void);
int x;
main()
{
x=10;
printf("x =%dn",x);
printf("x =%dn",fun1());
printf("x =%dn",fun2());
printf("x =%dn",fun3());
}
fun1(void)
{
x=x+10;
}
fun2(void)
{
int x
x=1;
return(x);
}
fun3(void)
{
x=x+ 10;
}
OUTPUT
:
x=10
x=20
x=1
x=30
70. EXTERNALVARIABLES
•
•
•
Onceavariable hasbeen declared asglobal, any function can
useit and change itsvalue
Then subsequent functions can reference only that newvalue
Global variable is that it is visible only from the point of
declaration to the end of the program
main()
{
y =5;
....
}
int y;
func1()
{
y =y + 1;
}
Asfor asmain is concerned, y is not defined. So,thecompiler
will issue an error message
Global variables are initialized to zero bydefault
Thestatement y =y +1 will assign1 to y.
•
•
•
71. EXTERNALDECLARATION
•
•
Themain cannot accessthe variable y asit hasbeendeclared
after the mainfunction
Thisproblem can be solved by declaring the variable withthe
storage classextern
main()
{
extern int y; /* external declaration */
....
}
func1()
{
extern int y; /* external declaration */
.....
}
int y; /* definition */
Although the variable y hasbeen defined after boththe
functions, the external declaration of y inside the function
informs the compiler that y is an integer type defined
somewhere else in the program
Theextern declaration does not allocate storage spacefor
variables
•
•
72. EXTERNALDECLARATION
main()
{
int i;
void print_out(void);
extern float height[];
....
print_out();
}
void print_out(void)
{
extern float height[];
int i;
......
.....
}
float height[SIZE];
•
•
An extern withinafunction provides the type information to
just that onefunction
We can provide type information to all functions within afile by
placing external declaration before any ofthem
73. EXTERNALDECLARATION
• Thedistinction between
definition anddeclaration
also applies to functions
Afunction is defined when
its parameters andfunction
body are specified
Thistells the compiler to
allocate spacefor the
function code andprovides
type information for the
parameters
Since functions are external
by default, we declare them
without the qualifierextern
voidprint_out(); is
equivalent to
extern voidprint_out();
•
•
•
•
•
extern float height[];
main()
{
int i;
void print_out(void);
....
print_out();
}
void print_out(void)
{
int i;
......
}
float height[SIZE];
74. STATICVARIABLES
• Thevalue of static variables persists until the end ofthe
program
Avariable can be declared static using the keyword
static
static int x;
static float y;
Astatic variable may be an internal or externaltype,
depending on the place ofdeclaration
•
•
75. EXAMPLE
void stat(void)
main()
{
int i;
for(i=1; i<=3;i++)
stat();
}
void stat(void)
{
static int x=0;
x=x+ 1;
printf("x =%dn",x);
}
OUTPUT
:
x=1
x=2
x=3
• If we had declared xasan
auto variable. The output
would be
X=1
X=1
X=1
76. STATICVARIABLES
Internal static variables
•
•
•
•
Declared inside afunction
The scope extend up to end of the function in which they are
defined
Similar to auto variables, except that they remain inexistence
(alive) throughout the remainder ofthe program
Static variable is initialized only once, when theprogram is
compiled. It is never initializedagain
External static variables
• Declared outside of all functions and is available to all the
functions in thatprogram
• Thedifference between astatic external variable and asimple
external variable isthat:
– the static external variable is available only within the file where it is
defined while the simple external variable canbe accessedby otherfiles
77. SCOPEOFFUNCTION
• To make a particular function accessible only to the
functions in the file in which it is defined and not to
any function in other files by defining that function
with the storage classstatic
78. REGISTERVARIABLES
•
•
Register accessis much faster than amemory access
We can make avariable to be placed in one ofthe
machine register instead of memoryusing
register int count;
Most compiler allow int or char variables to be
placed in the register
ANSIstandard does not restrict to any particulardata
type
Cwill automatically convert register variablesinto
non-register variables once the limit isreached
•
•
•
79.
80. MULTIFILEPROGRAMS
• More than one source file is compiled separately and
linked later to form an executable object code
This approach is very useful because any change in
one file does not affect other files thus eliminating
the need for recompilation of the entire program
Multiple source files can share avariable declaredas
an external variable
Variables that are shared by two or more files are
global variables and we must declare them
accordingly in one file and then explicitly define
them withextern in other file
•
•
•
83. MULTIFILEPROGRAMS
• Theextern specifier tells the compiler that thefollowing
variables types and names have already been declared
elsewhere and no need to create storage spacefor
them
It is the responsibility of the linker to resolve the
reference problem
Afunction defined in one file and accessedinanother
must include afunction declaration
Thedeclaration identifies the function asanexternal
function whose definition appearselsewhere
We place suchdeclarations at the beginning of thefile,
before all functions
Although all functions are external, it would be good
practice to explicitly declare suchfunctions withstorage
classextern
•
•
•
•
•