UNIT V User Defined Functions
UNIT V User Defined Functions
CHAPTER IX
USER-DEFINED FUNCTIONS
1
9.1 INTRODUCTION
• C function can be classified into two categories, namely
(i) library functions
(ii) user-defined function.
• Main() is an example of user-defined functions.
• While printf() and scanf() belong to the category of library functions.
• The main distinction between these two categories is that library functions are
not required to be written by us whereas a user- defined function has to be
developed by the user at the time of writing a program.
2
9.2 NEED FOR USER-DEFINED
FUNCTION
• main() function indicates where the • So in such situation, we may repeat the
program has to begin its execution. program statements wherever they are
• While it is possible to code any program needed.
utilizing only main function but it leads
to a lot of problem. • Another approach is to design a function
• Problem is that the program may that can be called and used whenever
become too large and complex and as a required.
result the task of debugging, testing, and
maintaining becomes difficult. • This saves both time and space.
• If a program is divided into functional • Top-down modular programming using
parts, then each part may be function have the following advantage.
independently coded and later combined
into single unit. 1. The length of a source program can be
• These subprograms called ‘function’ are reduced by using function at appropriate
much easier to understand, debug and places.
test. 2. It is easy to locate and isolate a faulty
• There are times when certain type of function for further investigations.
operation or calculation is repeated at
many points throughout a program. 3. A function may be used by many other
programs.
3
Top-down modular programming using functions
Main program
B1 B2
4
9.3 A MULTIPLE-FUNCTION PROGRAM
main()
• A function is a self-contained code that {
--------
performs a particular task. --------
• Once a function has been designed , it can function1(); call
--------
be treated as a block-box that takes some --------
data from the main program and return a function2(); call
--------
value. --------
• Every c program can be designed using the function3(); call
--------
collection of these black boxes known as }
function. function1()
{
• Any function can call any other function. --------
--------
• It can call itself. }
• A called function can also can call another function2()
{
function. R --------
• A function can be called more than once. E --------
}
• The function can be placed in any order. T function13)
{
• A called function can be placed either
U --------
before or after the calling function. R --------
}
N
5
9.4 MODULAR PROGRAMMING
• Modular programming is a strategy • Some characteristics of modular
applied to the design and programming are:
development of software systems.
• It is defined as organizing a large 1. Each module should do only one
program into small, independent thing.
program segments called modules 2. Communication between modules is
that are separately named and allowed only by a calling module.
individually callable program units.
• These modules are carefully 3. A module can be called by one and
integrated to become a software only one higher module.
system that satisfies the system 4. No communication can take place
requirements. directly between modules that do not
• It is basically a “divide-and-conquer” have calling-called relationship.
approach to problem solving. 5. All modules are designed as single-
• Modules are identified and designed entry, single-exit systems using
such that they can be organized into a control structure.
top-down hierarchical structure.
6
9.5 ELEMENTS OF USER-DEFINED
FUNCTION
• There are three elements of user- • The program that calls the function is
defined function. referred to as the calling program or
1. Function Definition calling function.
2. Function Call • The calling program should declare
3. Function Declaration any function that is to be used later in
the program.
• This is known as the function
• The function definition is an declaration or function prototype.
independent program module that is
specially written to implement the
requirement of the function
• In order to use this function we need
to invoke it at a required place in the
program. This is known as the
function call.
7
9.6 DEFINITION OF FUNCTIONS
• A function definition, also known as a general format of a function definition to
function implementation shall include implement these two parts is given below.
the following elements. function_type function_name(parameter list)
1. Function name {
local variable declaration;
2. Function type
executable statement1;
3. List of parameters
executable statement2;
4. Local variable declarations ………….
5. Function statements ………….
6. A return statement return statement;
}
• All the six elements are grouped into • The first line function_type
two parts, namely, function_name(parameter list) is known as
the function header and the statements
1. Function header (First three elements) within the opening and closing braces
2. Function body (Second three elements) constitute the function body, which is a
compound statement.
8
Function Header Formal Parameter List
• The function header consists of three • The parameter list declares the variables
parts: The function type(also known as that will receive the data sent by the
return type, the function name and the calling program.
formal parameter list. Note that a
• They serve as input data to the function to
semicolon is not used at the end of the
carry out the specified task.
function header.
• Since they represent actual input values,
Name and Type
they are often referred to as formal
• The function type specifies the type of parameters.
value that the function is expected to
• These parameters can also be used to send
return to the program calling the function.
values to the calling programs.
• If the return type is not explicitly
• These parameters are also known as
specified, c will assume that it is an
arguments.
integer type.
Examples
• If the function is not returning anything,
then we need to specify the return type as float quadratic(int a, int b, int c) { ….. }
void. • Remember, there is no semicolon after the
• Remember, void is one of the closing parenthesis.
fundamental data types in C. • Declaration of parameter variables cannot
• The function name is any valid C be combined.
identifier and therefore must follow the • That is, int sum(int a,b) is illegal.
same rules of formation as other variable • A function need not always receive values
names in C. from the calling program.
• The name should be appropriate to the • In such cases, functions have no formal 9
task performed by the function. parameters.
• To indicate that the parameter list is • The body enclosed in braces, contains three
parts, in the order given below:
empty, we use the keyword void 1. Local declarations that specify the variables
between the parentheses as in needed by the function.
void printline(void) 2. Function statements that perform the task of the
function.
{ 3. A return statement that returns the value
………… evaluated by the function.
• If a function does not return any value we can
} omit the return statement.
• This function neither receives any input • However note that its return type should be
specified as void.
values nor returns back any value.
• Again it is nice to have a return statement
• Many compilers accept an empty set of even for void functions.
parentheses, without specifying Return Values And Their Types
anything as in • If a function return value then it is done
through the return statement.
void printline() • While it is possible to pass to the called
function any number of values, the called
• But, it is a good programming style to function can only return one value per call, at
use void to indicate a null parameter list. the most.
Function Body • The return statement can take one of the
following forms
• The function body contains the return;
declarations and statement necessary for or
performing the required task. return(expression);
10
• The first, the ‘plain’ return does not Function Calls
return any value; it acts much as the • A function can be called by simply
closing brace of the function. using the function name followed by
• When a return is encountered, the a list of actual parameters , if any,
control is immediately passed back to enclosed in parentheses.
the calling function. Example
main()
Example {
int mul (int x, int y) int y;
{ y=mul(10,5);
int result; printf(“%d\n”,y);
result =x*y; }
return result; • When the compiler encounters a
} function call, the control is transferred
to the function mul().
• It return the value of p which is the
product of the values of x and y, and • This function is then executed line by
the type of return value is int. line as described and a value is
returned
• when a return statement is
encountered.
• This value is assigned to y.
11
• A function call is a postfix
expression. The operator (..)is at a Note:
very high level of precedence.
• Therefore, when a function call is 1. If the actual parameters are more than
used as a part of an expression, it will the formal parameters, the extra
be evaluated first, unless parentheses actual arguments will be discarded.
are used to change the order of 2. On the other hand, if the actuals are
precedence. less than the formals, the unmatched
• In a function call, the function name formal arguments will be initialized to
is the operand and the parentheses set some garbage.
which contains the actual parameters 3. Any mismatch in data types may also
are the operator. result in some garbage values.
• The actual parameters must match the
function’s formal parameters in type,
order and number.
• Multiple actual parameters must be
separated by commas.
12
9.7 FUNCTION DECLARATION
A function declaration consists of four Example
parts. void main()
• Function type {
• Function name int sum(int a,int b);
• Parameter list --------
• Terminating semicolon --------
Syntax }
Function-type function-name int sum(int a, int b)
(parameter list); {
• The function declaration appear in the int c;
main function. c=a+b;
• Here function-type indicate the type return(c);
of value that the function return.
• Function-name is name of the }
function.
• Parameter list is an arguments list.
13
Points to note
1. The parameter list must be separated by commas.
2. The parameter names do not need not to be the same in the prototype declaration
and the function definition.
3. The types must match the types of parameters in the function definition, in number
and order.
4. Use of parameter names in the declaration is optional.
5. If the function has no formal parameters then the list is written as void.
6. The return type is optional, when the functions returns int type data.
7. The return type must be void if no value is returned.
8. When the declared types do not match with the types in the function definition,
compiler will produce an error.
Example
14
Prototype : yes or no Parameters Everywhere
• Prototype declarations are not Parameters (arguments0 are used in the
essentials. following places:
• If a function has not been declared 1. in declaration (prototype)
before it is used, C will assume that --- formal parameters
its details available at the time of 2. in function call
linking.
• Since the prototype is not available, C ---actual Parameters
will assume that the return type is an 3. in function definition
integer and that the types of ---formal Parameters
parameters match the formal • The actual Parameters used in calling
definition. statement may be simple constants,
• If these assumptions are wrong, the variables or expressions.
linker will fail and we will have to • The formal and actual Parameters
change the program. must match exactly in type, order and
number.
• Their names do not need to match.
15
9.8 CATEGORY OF FUNCTIONS
16
9.8.1 NO ARGUMENTS AND NO RETURN
VALUES
• When a function has no arguments, it does not receive any data from the calling
function .
• Similarly, when it does not return value, the calling function does not receive
any data from the called function.
• Ie, there is no data transfer between the calling function and the called function.
function1() function2()
{ no input {
---------- ----------
---------- ----------
function2(); ----------
---------- no output ----------
---------- }
}
17
EXAMPLE 1
#include <stdio.h> for(i=2; i <= n; ++i)
void primeno(); {
int main() if( n%i == 0)
{ {
primeno();// argument is not passed flag = 1;
return 0; }
} }
if (flag == 1)
/* return type is void meaning
doesn't return any value*/ printf("%d is not a prime number.", n);
void primeno()
else
{
int n, i, flag = 0; printf("%d is a prime number.", n);
printf("Enter a positive integer value: "); }
scanf("%d",&n);
18
EXAMPLE 2
void printline()
#include <stdio.h>
{
#include <conio.h>
int i;
void printline();
for (i=0;i<=20;i++)
void si(); printf(“%c”,’-’);
int main() printf(“\n”);
{ }
clrscr(); void si()
printline(); {
si(); int p,n,r;
float interest;
printline();
printf(“Enter principal, no. of years and
return 0; rate of interest\n”);
} scanf(“%d%d%d”,&p,&n,&r);
interest=p*n*r/100.0;
printf(“Interest =%f”,interest);
getch();
}
19
9.8.2 Function with arguments and no return
values
• The function that takes argument but no return value.
• The functions receives the arguments from the calling function but does not
send back any value to calling function.
function1() function2(f)
{ {
----------
---------- values of ----------
function2(a); arguments ----------
---------- ----------
---------- ----------
no
} }
return
value
20
EXAMPLE
#include <stdio.h> void printline()
#include <conio.h> {
void printline(); int i;
void si(int,int,int); for (i=0;i<=20;i++)
void main() printf(“%c”,’-’);
{ printf(“\n”);
int p1,n1,r1; }
clrscr();
printf(“Enter principal, no. of years void si(int p,int n,int r)
and rate of interest\n”); {
scanf(“%d%d%d”,&p1,&n1,&r1); float interest;
printline();/*no arguments*/ interest=p*n*r/100.0;
si(p1,n1,r1);/* with arguments*/ printf(“Interest =%f”,interest);
printline(); }
getch();
}
21
9.8.3 FUNCTION WITH ARGUMENTS AND RETURN
VALUES
• A self-contained and independent
function should behave like a black
box that receive a predefined form of
input and outputs a desired value. function1() function2(f)
{ values {
Such function will have two-way data
---------- of ----------
communication.
---------- arguments ----------
• The called function receives the
arguments from the calling function function2(a); ----------
function
and send back value to calling ---------- return (e);
---------- result }
function.
}
22
EXAMPLE
#include <stdio.h> void printline()
#include <conio.h> {
void printline(); int i;
float si(int,int,int); for (i=0;i<=20;i++)
void main() printf(“%c”,’-’);
{ printf(“\n”);
int p1,n1,r1; }
float intamt;
clrscr(); float si(int p,int n,int r)
printf(“Enter principal, no. of years {
and rate of interest\n”); float interest;
scanf(“%d%d%d”,&p,&n,&r); interest=p*n*r/100.0;
printline();/*no arguments*/ return(interest);
intamt =si(p1,n1,r1);/* with }
arguments*/
printf(“simple interest= %f”,intamt);
printline();
getch();
}
23
The following events occur, in order, when the above function call is executed
1. The function call transfers the control along with copies of the values of the actual
arguments to the function si where the formal parameters p, n and r are assigned
the actual values of p1,n1 and r1 respectively.
2. The function si is executed line by line until the return(interest) statement is
encounters. At this point, the float value of interest is passed back to the function
call in the main and the following indirect assignment occurs:
Si(int p1,int n1,int r1)=interest;
3. The calling statement is executed normally and the returned value is thus assigned
to intamt, a float variable.
24
9.8.4 Function with no arguments and return
values
• The called function does void main()
not receive any arguments {
but return value to the int n;
calling function. n=get_no();
Example printf(“%d”,n);
• getchar() function does not getch();
receive any arguments
}
from the calling function
but return a value. int get_no()
Example {
#include <stdio.h> int no;
#include <conio.h> scanf(“%d”,&no);
int get_no(); return(no);
}
25
9.8.5 Function that return multiple values
• The mechanism of sending back information Example
through arguments is achieved using what are #include <stdio.h>
known as the address operator (&) and #include <conio.h>
indirection operator (*).
void mathoperation(int ,int ,int *,int *);
• The arguments not only to receive
information but also to send back information void main()
to the calling function. {
• The arguments that are used to “send-out” int x=5, y=7,s,d;
information are called output parameters. clrscr();
Rules for pass by pointers. mathoperation(x,y,&s,&d);
1. The types of the actual and formal parameters printf(“s=%d\t d=%d”,s,d);
must be same. }
2. The actual arguments must be local and void mathoperation(int a, int b, int *sum, int *diff)
address variable. {
3. The formal arguments in the function header *sum=a+b;
must be prefixed by the indirection operator.
*diff=a-b;
4. In the prototype, the arguments must be
prefixed by the symbol *. }
5. To access the value of an actual argument in
the called function, we must use the
corresponding formal argument prefixed with
the indirection operator.
26
9.9 NESTING OF FUNCTIONS
• A called function can call another
function. float ratio(int x, int y, int z)
• A function can call another function is {
called nesting of function. if (diff(y,z))
Example return(x/(y-z));
calculate the ratio a/(b-c) else
float ratio(int x, int y, int z); return(0.0);
int diff(int x,int y); }
void main()
{ int diff(int y1,int z1)
int a,b,c; {
clrscr(); if (y1 != z1)
printf(“Enter the value of a, b and c\n”); return (1);
scanf(“%d%d%d”, &a, &b, &c); else
printf(“Ratio = %f”, ratio(a,b,c)); return(0);
getch(); }
}
27
9.10 RECURSION
• When a called function in turn calls another function a process of “chaining” occurs.
Recursion is a special case of this process, where a function calls itself.
• A very simple example of recursion
main()
{
printf(“this is an example of recursion”);
main();
}
• when executed, this program will produce an output something like this:
o/p: this is an example of recursion
this is an example of recursion
this is an example of recursion
this is an example of recursion
this is an example of
28
Example
/*Factorial of a given no
N!=n*(n-1)*(n-2)*…….*1 */
#include <stdio.h> int factorial(int no)
#include <conio.h> {
int factorial(int no); int f;
void main() if (no==1)
{ return(1);
int n; else
int fact; f=no*factorial(no-1);
clrscr(); return (f);
printf(“Enter the value of n\n”); }
scanf(“%d”,&n);
fact=factorial(n);
printf(“Factorial of %d = %d”,n,fact);
getch();
}
29
9.11 PASSING ARRAYS TO FUNCTIONS
One-Dimensional Arrays • The largest function header might
look like:
• Like the values of simple variables, it float largest(float array[],int size)
is also possible to pass the value of an
array to a function. • The function largest is defined to take
• To pass a one-dimensional array to a two arguments, the array name and
called function, it is sufficient to list the size of the array to specify the
the name of the array, without any number of elements in the array.
subscripts, and the size of the array as • The declaration of the formal
argument
arguments. array is
Example float array[];
largest(a,n); • The pair of brackets informs the
• Will pass the whole array a to the compiler that the argument array is
an array of numbers.
called function. • It is not necessary to specify the size
• The called function expecting this call of the array here.
must be appropriately defined.
30
#include <stdio.h>
void main() • In C, the name of the array represent the
address of its first element.
{
• By passing the array name, we are, in fact,
float largest(float a[],int n);
passing the address of the array to the
float value[5]={1.1,3.7,-2.6,5.9,1.2}; called function.
printf(“Largest =%f”,largest(value,5)); • The array in the called function now refers
} to the same array stored in the memory.
float largest(float a[], int n) • Therefore, any changes in the array in the
{ called function will be reflected in the
int i; original array.
float max; • Passing addresses of parameters to the
function is referred to as pass by address
max=a[0];
( or pass by pointers)
for(i=1;i<n; i++)
{ A[0] =1.1max
Three rules to pass an Array to a function:
if (max <= a[i])
A[1] = 3.7-max 1. The function must be called by passing only
A[2]= -2.6 the name of the array.
{
A[3]= 5.9 max 2. In the function definition, the formal
max=a[i];
A[4]= 1.2 parameter must be an array type; the size of
} the array does not need to be specified.
} 3. The function prototype must show that the
argument is an array.
return(max);
}
31
Example
Two-Dimensional Arrays
#include <stdio.h>
• Like simple arrays, we can also pass #include<conio.h>
multi-dimensional arrays to functions. float average(int x[][n],int m,int n);
• The approach is similar to the one we void main()
{
did with one-dimensional arrays.
int m=3,n=3,i,j,a[3][3];
The rules are simple. float mean;
1. The function must be called by clrscr();
passing only the array name. printf(“enter the array elements one by one\m”);
for(i=0;i<m;i++)
2. In the function definition, we must
for(j=0;j<n;j++)
indicate that the array has two- scanf(“%d”,&a[i][j]);
dimensions by including two sets of mean=average(a[][n],m,n);
brackets. printf(“average= %f”,mean);
3. The size of the second dimension getch();
must be specified. }
float average(int x[][n],int m,int n)
4. The prototype declaration should be {
similar to the function header. int i,j;
float sum=0.0;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
sum=sum+x[i][j];
return(sum/(m*n));
32
}
Passing Strings to Functions #include <stdio.h>
The strings are treated as character arrays void passstring (char str[]);
in C and therefore the rules for char s1[50];
passing strings to function are very int main()
similar to those for passing arrays to
the functions. {
1. The string to be passed must be char s[50];
declared as a formal argument of the printf(“Enter string: ");
function when it is defined. gets(s);
2. The function prototype must show /* passing string to a function.*/
that the argument is a string. passstring(s);
3. A call to the function must have a return 0;
string array name without subscripts }
as its actual argument.
void passstring (char str[])
{
printf(“String output: ");
puts(str);
}
33
Call by Value and Call by reference 2. Pass by pointers (Call by reference)
• The technique used to pass data from • The memory addresses of the
one function to another is known as variables rather than the copies of
parameter passing. values are sent to the called function.
Parameter passing can be done in two • In this case, the called function
ways. directly works on the data in the
1. pass by value (also known as call by calling function and the changed
value) value is available in the calling
2. pass by pointers (also known as call function for its use.
by reference) • pass by pointers method is often used
when manipulating arrays and strings.
1. Pass by value (call by value) • This method is also used when we
require multiple values to be returned
In pass by value, by the called function.
• The value of actual parameters are
copied to the variables in the
parameter list of the called function.
• The called function works on the
copy and not on the original values of
the actual parameters.
• This ensures that the original data in
the calling function cannot be
changed accidentally.
34
9.12 Scope, Visibility and Lifetime of Variables
Storage classes are • The variables may also be
categorized, depending on the place
1. Automatic variables
of their declaration, as
2. External variables
Internal (local) or
3. Static variables
External(global)
4. Register variables
• Internal (local) variables are those
• The scope of the variable determines which are declared within a particular
over what region of the program a function.
variable is actually available for use
• External variables are declared
(‘active’)
outside of any function.
• Longevity refers to the period during
which a variable retains a given value
during execution of a program
(‘alive’).
• So longevity has a direct effect on the
utility of a given variable.
• The visibility refers to the
accessibility of a variable from the
memory. 35
Automatic variables void main()
• Automatic variables are declared {
inside a function in which they are to int x=100;
be utilized. function2();
printf(“The value of x inside main =%d”,x);
• They are created when the function is getch();
called and destroyed automatically }
when the function is exited.
void function1()
• Automatic variables are private {
variable to the function in which they int x=10;
are declared . printf(“The value of x inside function1() =%d”,x);
• Automatic variables are also called as }
local or internal variables. void function2()
• A variable declared inside a function {
without storage class specification is, int x=1;
by default. function1();
printf(“The value of x inside function2() =%d”,x);
Example }
OUTPUT
#include <stdio.h> The value of x inside function1() =10
#include<conio.h>
void function1(); The value of x inside function2() =1
void function2();
The Value of x inside main = 100
36
External variables • The variable no and l are available for use
• Variables that are both alive and active in all the three functions.
throughout the program are known as • In case a local variable and a global
external variables. variable have the same name, the local
• They are also kown as global variables. variable will have precedence over the
• Unlike local variables, global variables global one in the function where it is
can be accessed by any function in the declared.
program.
• External variables are declared outside a Example
function. int count;
Example main()
int no;
float l=3.2; {
main() count=10;
{ ---------
--------- }
---------
}
function1()
function1() {
{ int count=0
--------- ---------
---------
}
}
function2() • When the function1() references the
{ variable count, it will referencing its local
--------- variable count(=0), not the global one.
---------
}
37
Example program f1()
#include <stdio.h> {
#include<conio.h> int x;
int f1(void); x=10;
int f2(void); return(x);
int f3(void); }
int x; f3()
void main() {
{ x=x+10;
x=100; return(x);
clrscr(); }
printf(“x=%d\n”,x); Output
printf(“x=%d\n”,f1()); x=100
printf(“x=%d\n”,f2()); x=1000
printf(“x=%d\n”,f3()); x=10 Local variable
getch(); x=1010
} • Once a variable has been declared as
f1() global, any function can use it and change
{ the value .
x=x*10; • Then subsequent functions can reference
only that new value.
return(x);
} 38
Global variable as parameters External declaration
• Using global variables as parameters • This tells External variables are also
for passing values produces problems. known as global variables.
• The values of global variables which • These variables are defined outside
are sent to the called function may be the function.
changed without knowledge by the
• These variables are available globally
called function.
throughout the function execution.
• Functions are supposed to be
• The value of global variables can be
independent and isolated modules.
modified by the functions.
This character is lost, if they use
global variables. • “extern” keyword is used to declare
and define the external variables.
• It is not immediately apparent to the
reader which values are being sent to Scope − They are not bound by any
the called function. function. They are everywhere in the
program i.e. global.
• A function that uses global variables
suffers from reusability. Default value − Default initialized value
of global variables are Zero.
Lifetime − Till the end of the execution
of the program.
39
1. External variables can be declared #include <stdio.h>
number of times but defined only extern int x = 32;
once. int b = 8;
2. “extern” keyword is used to extend int main()
the visibility of function or variable. {
3. By default the functions are visible auto int a = 28;
throughout the program, there is no extern int b;
need to declare or define extern printf("The value of auto variable : %d\n", a);
functions. It just increase the printf("The value of extern variables x and b :
redundancy. %d,%d\n",x,b);
4. Variables with “extern” keyword x = 15;
are only declared not defined. printf("The value of modified extern variable x :
%d\n",x);
5. Initialization of extern variable is return 0;
considered as the definition of the }
extern variable. Output
The value of auto variable : 28
The value of extern variables x and b : 32,8
The value of modified extern variable x : 15
40
Consider the program segment External declaration
main() • The above problem can be solved by
{ declaring the variable with the storage class
y=5; extern.
-------- Example
-------- main()
} {
int y; extern int y;
f1() --------
{ --------
-------- }
y=y+1; f1()
-------- {
} extern int y;
• As for as main is concerned ,y is not --------
defined. --------
• So, the compiler will issue an error }
message. • The external declaration of y inside the
• Unlike local variables, global variables are function informs to the compiler that y is an
initialized to zero by default. integer type defined somewhere else in the
• So the value of y in f1 is assigned to 1. program
41
Static variables Example1
• Static variables are initialized only once.
• The compiler persists with the variable till #include <stdio.h>
the end of the program. int main()
• Static variables can be defined inside or {
outside the function. auto int a = -28;
• They are local to the block. static int b = 8;
• The default value of static variables is printf("The value of auto variable : %d\n", a);
zero.
printf("The value of static variable b:%d\n",
• The static variables are alive till the b);
execution of the program.
if(a!=0)
Syntax
printf("The sum of static variable and auto
static datatype variable_name = value; variable : %d\n",(b+a));
return 0;
• datatype − The datatype of variable like }
int, char, float etc.
Output
• variable_name − This is the name of
variable given by user. The value of auto variable : -28
• value − Any value to initialize the The value of static variable b : 8
variable. By default, it is zero. The sum of static variable and auto variable : -20
42
Example 2 Output
#include<stdio.h> x=11
#include<conio.h> x=12
void stat(void); x=13
void main()
{ • An external static variable is declared
int i; outside of all functions and is
for (i=1;i<=3;i++) available to all the functions in that
program.
stat();
• The difference between a static
getch(); external variable and a simple
} external variable is that the static
void stat(void) external variable is available only
{ within the file where it is defined
static int x = 10; while the simple external variable can
be accessed by other files.
x=x+1;
printf(“”x=%d\n”,x);
}
43
Register variables Output
• Register variables tell the compiler to store the The value of register variable b : S
variable in CPU register instead of memory. The sum of auto and register variable : 18
• Frequently used variables are kept in registers
and they have faster accessibility. • Register keyword can be used with pointer
• We can never get the addresses of these also.
variables. • It can have address of memory location.
• “register” keyword is used to declare the register • It will not create any error.
variables.
Example
• Scope − They are local to the function.
#include<stdio.h>
• Default value − Default initialized value is the
garbage value. int main()
• Lifetime − Till the end of the execution of the {
block in which it is defined. int i = 10;
Example register int *a = &i;
#include <stdio.h> printf("The value of pointer : %d", *a);
int main() getch();
{ return 0;
register char x = 's'; }
register int a = 10; Output
auto int b = 8; The value of pointer : 10
printf(“The value of register variable b : %c\n",x);
printf("The sum of auto and register variable : %d",(a+b));
return 0;
}
44
Storage class Where declared Visibility lifetime
None Before all functions in a file Entire file plus other files Entire program
(may be initialized) where variable is declared (global)
with extern
Extern Before all functions in a file Entire file plus other files global
(cannot be initialized) extern where variable is declared
and the file where originally
declared as global
Static Before all functions in a file Only in that file global
None or auto Inside a function (or a block) Only in that function or a Until end of
block function or block
register Inside a function (or a block) Only in that function or a Until end of
block function or block
45
UNIT – IV
CHAPTER X
STRUCTURES AND UNIONS
46
10.1 INTRODUCTION
• Arrays can be used to represent a • Structure is a method of packing
group of data items that are belongs to data of different types.
the same type. • A structure is a convenient method of
• Arrays are used to store large set of handling a group of related data items
data and manipulate them. of different data types.
• disadvantage of arrays is that all the
elements stored in an array are to be
of the same data type.
• If we need to use a collection of
different data type items it is not
possible using an array.
• When we require using a collection of
different data items of different data
types we can use a structure.
47
10.2 Array vs structures
48
10.3 DEFINING A STRUCTURE
Syntax struct book_bank
struct tag_name {
{ char title[20];
data type member1; char author[15];
data type member2; int pages;
… float price;
… };
};
Note • Create a structure Book_bank to store book
details.
1. The template is terminated with a
semicolon. • The keyword struct declares a structure to
holds the details of four fields namely title,
2. While the entire definition is considered as author, pages and price.
a statement, each member is declared
independently for its name and type in a • These are members or elements of the
separate statement inside the template. structures.
3. The tag name can be used to declare • Each member may belong to different or
structure variables of its type, later in the same data type.
program. • The tag name can be used to define objects
that have the tag names structure.
• The structure we just declared is not a
variable by itself but a template for the
structure.
49
10.4 DECLARING STRUCTURE
VARIABLE
To access structure item, we require to We can declare structure variables using
create the tag name any where in the
structure variable (object). program.
• A structure variable declaration is Example
similar to the declaration of variables struct lib_books book1,book2,book3;
of any other data types.
It includes the following elements: • Declares book1,book2,book3 as
1. The keyword struct. variables of type struct lib_books
2. The structure tag name. each declaration has four elements of
3. List of variable names separated by the structure lib_books.
names. • Structures do not occupy any memory
4. A terminating semicolon. until it is associated with the structure
variable such as book1.
Syntax
struct structure_name variable_name;
50
We can also combine both template
• Declares book1, book2, book3 as
declaration and variables declaration
structure variables representing 3
in one statement.
books but does not include a tag name
Example for use in the declaration.
struct lib_books • This approach is not recommended
{ for the two reasons.
char title[20]; 1. Without tag name, we cannot use it
char author[15]; for future declarations.
int pages; 2. Normally, structure definitions appear
float price; at the beginning of the program file,
before any variables or functions are
} book1,book2,book3;
defined. They may also appear before
The use of tag name is optional. the main, along with macro
Example definitions, such as #define. In such
struct cases, the definition is global and can
{ be used by other functions as well.
…
…
…
} book1, book2, book3 ;
51
10.5 Type-Defined Structures
Syntax
typedef struct
{
--------
type member1;
type member2;
--------
}type name;
• The type-name represents structure definition associated with it and therefore, can
be used to declare structure variables as
type-name variable1,variable2,…………….;
Note
1. The name type-name is the type definition name ,not a variable.
2. We cannot define a variable with typedef declaration.
52
10.6 ACCESSING STRUCTURE MEMBERS
• The link between a member and a Or We can use scanf statement to assign
variable is established using the values like
member selection operator ‘.’ which scanf(“%s”,book1.title);
is known as dot operator or period scanf(“%d”,&book1.pages);
operator.
Example
book1.price
• is the variable representing the price
of book1 and can be treated like any
other ordinary variable.
• we can assign variables to the
members of book1
strcpy(book1.title,”basic”);
strcpy(book1.author,”Balagurusamy”);
book1.pages=250;
book1.price=285.0;
53
Example program scanf("%s",s2.name);
#include<stdio.h> printf("Enter the roll number of
#include<conio.h> student2:");
struct student scanf("%d",&s2.num);
{ printf("Enter the marks of student2:");
char name[20]; scanf(“%d",&s2.mark);
int num; printf(“Students Details\n");
int mark; printf(“Student 1 details\n”);
}; printf("%s\n",s1.name);
void main() printf("%d\n",s1.num);
{ printf(“%d\n",s1.mark);
struct student s1,s2; printf(“Student 2 details\n”);
clrscr(); printf("%s\n",s2.name);
printf("Enter the name of student1:"); printf("%d\n",s2.num);
scanf("%s",s1.name); printf(“%d",s2.mark);
printf("Enter the roll number of getch();
student1:"); }
scanf("%d",&s1.num);
printf("Enter the marks of student1:");
scanf(“%d",&s1.mark);
printf("Enter the name of student2:");
54
10.7 STRUCTURE INITIALIZATION
• A structure variable can be initialized Example2
at compile time. main()
Example 1 {
main() struct st_record
{ {
struct int weight;
{ float height;
int weight; };
float height; struct st_record student1={50,170.26};
} student={50,170.26}; struct st_record student2={60,180.75};
………… …………
………… …………
} }
• This assigns 50 to student.weight and
170.26 to student.height.
• There is one-to-one correspondence
between the members and their
initializing values.
55
Example 3 1. The name of the variable to be
struct st_record declared.
{ 2. The assignment operator =.
int weight; 3. A set of values for the members of
float height; the structure variable, separated by
}student1={50,170.26}; commas and enclosed in braces.
4. A terminating semicolon.
main()
{ Rules for initializing structures
struct st_record student2={60,180.75}; 1. We cannot initialize the individual
………… members inside the structure
………… template.
} 2. The order of values enclosed in
• The c language does not permit the braces must match the order of
initialization of individual structure members in the structure definition.
members within the templates.
• The initialization must done only in 3. It is permitted to have a partial
the declaration of the actual variables. initialization. We can initialize only
• The compile-time initialization of a the first few members and leave the
structure variable must have the remaining blank. The uninitialized
following elements. members should be only at the end of
1. The keyword struct the list.
2. The structure tag_name.
4. The uninitialized members will be
56
assigned default values.
10.8 COPYING & COMPARING STRUCTURE VARIABLES
copy void main()
• Two variables of the same structure type can be {
copied .
int x;
Example
• If student1 and student2 belong to the same struct class stud1={101, “anu”,89};
structure then struct class stud2={102, “banu”,80};
student1=student2; struct class stud3;
student2= student1;
stud3=stud2;
Comparision x= ((stud3.no==stud2.no) && (stud3.marks ==
• The following statements are not permitted in c.
stud2.marks))?1:0;
student1 == student2
student1 != student2 if (x=1)
• C does not permitted any logical operators on {
structure variables. printf(“\n student2 and student3 same\n”);
• We can compare members individually.
printf(“%d%s%d”,stud3.no,stud3.name,stud3.marks)
;
structure class
{ }
int no; else
char name[20]; {
int marks; printf(“student2 and student3 are different”);
};
}
}
57
10.9 ARRAYS OF STRUCTURES
• Declaring an array of structure is same as Example
declaring an array of fundamental types. struct student
• An array is a collection of elements of the {
same type. char name[20];
• In an array of structures, each element of an int num;
array is of the structure type.
• An array of structure is stored inside the int mark;
memory in the same way as a multi- };
dimensional array. struct student stud[10];
Syntax
struct tag_name
{
data type member1;
data type member2;
…
…
};
struct tag-name struct_array[size];
58
EXAMPLE
#include<stdio.h> printf(“Enter the name of the student %d :”, i+1)
#include<conio.h> scanf(“%s”, stud[i].name);
struct student printf(“Enter the marks of the student %d :”, i+1)
{ scanf(“%d”, &stud[i].mark);
char name[20]; }
int num; for (i=0;i<n;i++)
int mark; {
}; printf(“Reg.no of the student %d : %d”,
struct student stud[10]; i+1,stud[i].num);
void main() printf(“Name of the student %d : %s”,
{ i+1,stud[i].name);
int i,n; printf(“Marks of the student %d : %d”,
i+1,stud[i].mark);
clrscr(); }
printf(“\n Enter the no. of students in a class:”); getch();
scanf(“%d”, &n); }
printf(“Enter the students detials one by one\n”);
for (i=0;i<n;i++)
{
printf(“Enter the reg.no of the student %d :”, i+1)
scanf(“%d”, &stud[i].num);
59
10.10 ARRAYS WITHIN STRUCTURES
• C permits the use of arrays as structure printf(“Enter the name of the student %d :”, i+1)
members. scanf(“%s”, stud[i].name);
Example printf(“Enter the marks of the student %d :”, i+1)
stud[i].total=0;
#include<stdio.h> for (j=0;j<3;j++)
#include<conio.h> {
struct student
scanf(“%d”, &stud[i].mark[j]);
{
char name[20]; stud[i].total= stud[i].total+stud[i].mark[j];
int num; }
int mark[3]; }
int total; for (i=0;i<n;i++)
};
{
struct student stud[10];
void main() printf(“\nReg.no of the student %d : %d”,
{ i+1,stud[i].num);
int i,n,j; printf(“\nName of the student %d : %s\n”,
clrscr(); i+1,stud[i].name);
printf(“\n Enter the no. of students in a class:”); for (j=0;j<3;j++)
scanf(“%d”, &n); printf(“Marks of the student %d \t: %d”,
printf(“Enter the students detials one by one\n”); i+1,stud[i].mark[j]);
for (i=0;i<n;i++)
printf(“\nTotal marks of the student %d : %d”,
{
i+1,stud[i].total);
printf(“Enter the reg.no of the student %d :”, i+1)
scanf(“%d”, &stud[i].num); }
getch();
}
60
10.11 STRUCTURES WITHIN STRUCTURES
• Structure within a structure is called
nested structure. • The members contained in the inner
Example structure namely da, hra and cca can
struct salary be reffered as
{
char name[20]; employee.allowance.da;
char dept[30]; employee.allowance.hra;
struct employee.allowance.cca;
{
int da; • A inner-most member in a nested-
structure can be accessed by chaining
int hra; all the concerned structures variables
int cca; with member using dot operator.
}allowance;
} employee;
61
10.12 STRUCTURES & FUNCTIONS
There are 3 methods to transferred structure • The general format of sending a copy of a
from one function to another. structure to the called function is
1. Pass each member of structure as an actual function_name(structure_variable_name);
argument of the function call. The actual • The called function format
arguments are then treated independently data_type
like ordinary variables. This is the most function_name(struct_variable_name)
elementary method and becomes
unmanageable and inefficient when the {
structure size is large. ………….
2. Passing of a copy of the entire structure to ………….
the called function. Since the function is return(expression);
working on a copy of the structure, any }
changes to structure members within the Note
function are not reflected in the original
structure. Therefore the necessary for the 1. The called function must be declared for
function to return the entire structure back its type, appropriate to the data type it is
to the calling function. expected to return.
3. Using pointers to pass the structure as an 2. The structure variable used as the actual
argument. argument and the corresponding formal
parameter in the called function must be of
the same struct type.
62
3. The return statement is necessary only void print_struct(struct student stu);
when the function is returning some data
back to the calling function. The void main()
expression may be any simple variable or {
structure variable or an expression using struct student stu = {"George", 10, 69};
simple variables print_struct(stu);
4. When a function returns a structure, it return 0;
must be assigned to a structure of identical }
type in the calling function.
void print_struct(struct student stu)
5. The called functions must be declared in
the calling function appropriately. {
printf("Name: %s\n", stu.name);
Example printf("Roll no: %d\n", stu.roll_no);
#include<stdio.h> printf("Marks: %d\n", stu.marks);
#include<conio.h> printf("\n");
/* structure is defined above all functions so it }
is global. */
struct student
{
char name[20];
int roll_no;
int marks;
};
63
10.13 UNIONS
• A union is a special data type available in • The union tag is optional and each
C that allows to store different data types member definition is a normal variable
definition, such as int i; or float f; or any
in the same memory location. other valid variable definition.
• We can define a union with many • At the end of the union's definition, before
members, but only one member can the final semicolon, you can specify one or
contain a value at any given time. more union variables but it is optional.
• Unions provide an efficient way of using Example
the same memory location for multiple-
purpose. union Data
Defining a Union {
union [union tag] int i;
{ float f;
member definition; char str[20];
} data;
member definition;
... • A variable of Data type can store an
member definition; integer, a floating-point number, or a
string of characters.
} [one or more union variables];
64
• It means a single variable, i.e., same #include <stdio.h>
memory location, can be used to store #include <string.h>
multiple types of data. union Data
• We can use any built-in or user defined {
data types inside a union based on your int i;
requirement.
float f;
• The memory occupied by a union will be
char str[20];
large enough to hold the largest member of
the union. };
Example int main( )
• Data type will occupy 20 bytes of {
memory space because this is the union Data data;
maximum space which can be occupied by data.i = 10;
a character string. data.f = 220.5;
Accessing Union Members strcpy( data.str, "C Programming");
• To access any member of a union, we use printf( "data.i : %d\n", data.i);
the member access operator (.).
printf( "data.f : %f\n", data.f);
• The member access operator is coded as a
printf( "data.str : %s\n", data.str);
period between the union variable name
and the union member that we wish to return 0;
access. }
• The keyword union to define variables of Output: data.str : C Programming
union type.
65
10.14 BIT FIELDS
• A bit field is a set of adjacent bits whose • A signed bit field should have at least 2
size can be from 1 to 16 bits length. bits(one bit for sign).
• A word can therefore be divided into a • The field name is followed by a colon.
number of bit fields. • The bit-length is decided by the range of
• The name and size of bit fields are defined value to be stored.
using structure. • The largest value that can be stored is 2 n-,
Syntax where n is bit-length.
struct tag-name • The internal representation of bit fields is
{ machine dependent.
data-type name:bit-length; • It depends on the size of int and ordering of
data-type name:bit-length; bits.
…………….. 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
……………..
data-type name:bit-length;
};
• The data type is either signed int or name n ……………………. name2 name1
unsigned int and the bit-length is the no. of
bits used for a specified name.
66
Note Example
1. The first field always starts with the first #include <stdio.h>
bit of the word. #include <string.h>
2. A bit field cannot overlap integer struct
boundaries. Ie. The sum of lengths of all {
the fields in a structure should not be
more than the size of a word. In case, it unsigned int age : 3;
is more, the overlapping field is } Age;
automatically forced to the beginning of int main( )
the next word. {
3. There can be unnamed fields declared Age.age = 4;
with size. printf( "Sizeof( Age ) : %d\n", sizeof(Age) );
4. There can be unused bits in the word. printf( "Age.age : %d\n", Age.age );
5. We cannot take the address of a bit field Age.age = 7;
variable. This means we cannot use
scanf() function to read values into bit printf( "Age.age : %d\n", Age.age );
fields. We can neither use pointer to Age.age = 8;
access the bit fields. printf( "Age.age : %d\n", Age.age );
6. Bit fields cannot be arrayed. return 0;
7. Bit fields should be assigned values that }
are within the range of their size.. If we
try to assign larger values, behaviour
would be unpredicted.
67
References
1. E. Balagurusamy, ”Programming in ANSI C”, Seventh Edition, McGraw Hill Education India
Private Ltd, 2017.
2. https://www.tutorialspoint.com/cprogramming/
3. https://overiq.com/c-programming-101/structures-and-functions-in-c/
68