0% found this document useful (0 votes)
9 views23 pages

BIT104 SLM Library - SLM - Unit 10

Uploaded by

pavanmay227597
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views23 pages

BIT104 SLM Library - SLM - Unit 10

Uploaded by

pavanmay227597
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Principles of C Programming Unit 10

Unit 10 Function II and Storage Classes


Structure:
10.1 Introduction
Objectives
10.2 Passing Parameters to Function
Passing Parameter by Value
Passing Parameter by reference
10.3 Passing Arrays to Function
Passing a Multidimensional Array
Passing String
10.4 Storage Classes and Visibility
10.5 Automatic or Local Variables
10.6 Global Variables
10.7 Static Variables
10.8 External Variables
10.9 Summary
10.10 Terminal Questions
10.11 Answers
10.12 Exercises

10.1 Introduction
In the previous unit, we discussed how functions can be used to break large
problems into smaller ones and then solve it. We studied how functions can
be recursively called and used. In this unit, we will discuss about the various
ways of passing parameter to function, passing arrays and string to the
function. We will also discuss about the types of storage classes that are
used in C programs. We will study how these are useful in making the C
language a very powerful computing language.
As we discussed in the last unit, function is a “black box’’ into which we
have written part of our program. In C, functions exchange information by
means of formal parameters, actual parameters and return values. The term
formal parameter refers to any declaration within the parentheses following
the function name in a function declaration or definition; the term actual
parameters (argument) refers to any expression within the parentheses of a
function call. There are two ways to pass parameters to a function: pass by
value and pass by reference.
Sikkim Manipal University B2074 Page No.: 206
Principles of C Programming Unit 10

To solve a complex problem in practice, the programmer normally breaks


the problem into smaller pieces and deals with each piece of the problem by
writing one or two functions. Then, all the functions are put together to form
a complete program that can be used to solve the complex problem.
Variables are channels of communication within a program. We set a
variable to a value at one point in a program, and at another point (or points)
we read the value out again. In the complete program, there are variables
that have to be shared by all the functions. On the other hand, the use of
some variables might be limited to only certain functions. That is, the
visibility of those variables is limited, and values assigned to those variables
are hidden from many functions.
Limiting the scope of variables is very useful when several programmers are
working on different pieces of the same program. If they limit the scope of
their variables to their pieces of code, they do not have to worry about
conflicting with variables of the same name used by others in other parts of
the program.
In C, we can declare a variable and indicate its visibility level by designating
its scope. Thus, variables with local scope can only be accessed within the
block in which they are declared. For example, in some situations it may be
desirable to introduce certain “global” variables that are recognized through
the entire program. Such variables are defined differently as compared to
the usual “local” variables, which are recognized only within a single
function.
We will also discuss about static variables which can retain their values, so
that the function can be reentered later and the computation resumed with
same value of variable.
Finally, we may be required to develop a large, multi-function program in
terms of several independent files, with few functions defined within each
file. In such programs, the individual functions can be defined and accessed
locally within a single file, or globally within multiple files.
Objectives:
After studying this unit, you should be able to:
 explain the passing parameters by values and reference
 describe the passing array and string to function
Sikkim Manipal University B2074 Page No.: 207
Principles of C Programming Unit 10

 implement the concept of storage classes and visibility of variables


 explain the difference between automatic variables, global variables,
static variables and external variables.
 compile and execute a program made up of more than one source files.

10.2 Passing Parameters to Function


There are two ways to pass parameters to a function: pass by value and
pass by reference.
10.2.1 Passing Parameter by Value
In passing parameter by value mechanism, function receives the actual
values of arguments and assigned to corresponding formal parameters. In
other words, while calling to functions, copies of the passed variables are
created and assigned to the formal parameters. This mechanism is used
when we do not want to change the value of passed parameters.
Program 10.1: Program to Display swapping of two integer number
using mechanism of pass by value.
#include <stdio.h>
// function declaration
void swap( int p1, int p2 );
int main()
{
int a = 10;
int b = 20;

printf("Before swap: Value of a = %d and value of b = %d\n", a, b );


swap( a, b );
printf("After swap: Value of a = %d and value of b = %d\n", a, b );
}
void swap( int x, int y )
{
int t;
t = y;
y = x;
x = t;
printf("Value of x = %d and value of y = %d\n", x, y );
}
Before swap: Value of a = 10 and value of b = 20
Value of x = 20 and value of y = 10
After swap: Value of a = 10 and value of b = 20
Sikkim Manipal University B2074 Page No.: 208
Principles of C Programming Unit 10

Before calling swap(), value of a and b variable are 10,20 respectively.


While calling swap(), the variable x and y receives values 10 and 20
respectively. In swap (), we are interchanging value of x and y, so new value
of x and y are 20 and 10 respectively. After successful execution of function
swap (), control transfer to main function. The value of a and b in main
function remain unchanged i.e. 10 and 20 respectively.
In parameter passing by value mechanism changes made in formal
argument (variables receiving value in called function from calling function
that is x and y in above program) do not reflect in actual argument (variable
in function call i.e. a and b in function call swap (a, b)).
10.2.2 Passing Parameter by Reference
In passing parameter by reference mechanism, we are passing addresses
of the variables to a function instead of actual value of parameter. Each
variable has some fixed address which remains constant throughout
execution of program in memory. Using this address of variable, it is also
possible to access and modify the value of the variable by using pointer.
This mechanism is used when we want a function to do the changes in
passed parameters and reflect those changes back to the calling function.
Program 10.2: Program to swap value of integer variables using
passing parameter by reference mechanism:
#include<stdio.h>
void swap(int * x, int *y)
void main( )
{
int a = 10, b = 20 ;
printf("\nBefore a = %d b = %d", a, b ) ;
swap( &a, &b ) ;
printf ( "\nAfter a = %d b = %d", a, b ) ;
}
void exchange( int *x, int *y )
{
int t ;
t = *x ;
*x = *y ;
*y = t ;

Sikkim Manipal University B2074 Page No.: 209


Principles of C Programming Unit 10

}
Output:
Before a = 10 b = 20
After a = 20 b = 10

As we know int * x, means x is going to hold address (memory location) of


integer type of variable. In the program 10.2, we are passing address of
variables a, b to function swap, so while receiving we are using two pointers
to integer. Before calling swap () value of a and b are 10 and20 respectively.
As we are passing the address of a and b to function swap, when control
returns from the function values of a and b are swapped.
Generally we use parameter passing by value mechanism if we do not need
the changes made in calling function to reflect in called function. But if we
required the changes to reflect in called function, we use parameter passing
by reference mechanism.
Also, if we want to return more than one value to called function from calling
function we go for parameter passing by reference mechanism which is not
possible otherwise.
Self-Assessment Questions
1. The parameter passing by __________ is used when we do not want
to change the value of passed parameters.
2. In parameter passing by ________ mechanism only addresses of the
variables are passed to a function so that function can work directly
over the addresses.

10.3 Passing Arrays to Functions


An array name can be used as an argument to a function, thus permitting
the entire array to be passed to the function. To pass an array to a function,
the array name must appear by itself, without brackets or subscripts, as an
actual argument within the function call. The corresponding formal argument
is written in the same manner, though it must be declared as an array within
the formal argument declarations. When declaring a one-dimensional array
as a formal argument, the array name is written with a pair of empty square
brackets. The size of the array is not specified within the formal argument
declaration.

Sikkim Manipal University B2074 Page No.: 210


Principles of C Programming Unit 10

A function that takes an array as an argument does not know how many
elements are in the array. We should also pass the number of elements as
another argument to the function.
Program 10.3: The following program illustrates the passing of an array
from the main to a function. This program is used to find the average of n
floating point numbers.

#include<stdio.h>
float average(int, float[]); /* function prototype */
main()
{
int n, i;
float avg;
float list[100];

printf(“How many numbers:”);


scanf(“%d”,&n);
printf(“ Enter the numbers:”);
for(i=1;i<=n;i++)
scanf(“%f”, &list[i]);
avg=average(n, list); /* Here list and n are actual arguments */
printf(“Average=%f\n”, avg);
}
float average(int a, float x[ ])
{
float avg;
float sum=0;
int i;
for(i=0;i<a;i++)
sum=sum+x[i]; /* find sum of all the numbers */
avg=sum/a; /* find average */
return avg;
}

In function header, float average (int a, float x [ ]), first argument specifies
the sizes of the array x which is used in for loop and the second argument
the un-sized array x.
Sikkim Manipal University B2074 Page No.: 211
Principles of C Programming Unit 10

We can also specify the size of an array that is passed to a function. For
instance, in the following:
function(char str[16]);
is equivalent to the following statement:
function(char str[]);
Remember that the compiler can figure out the size for the un-sized array
str[].
10.3.1 Passing a Multidimensional Array
So far we have discussed the ways to pass a one-dimensional array to a
function. Let us now extend this to the case of a two-dimensional array. We
pass two-dimensional arrays in four ways as shown below:
1. An array to an array a[m][n] to b[m][n]
2. An array to a pointer a[m][n] to * p
3. An array to a one-dimensional pointer array a[m][n] to ( *q )[n]
4. An array to a two-dimensional pointer array a[m][n] to ( *q )[m][n]
Example 10.1: We will illustrate the use of these four methods through the
sample program. In this we pass a two dimensional array to four functions,
using each one of the methods mentioned above.
#include<math.h>
#include<stdio.h>
main()
{
int arr[ ][2]={{11,12},{21,22},{31,32},{41,42},{51,52}};
int i,m,n,*j;
m=5;
n=2;
print(arr,m,n);
show(arr,m,n);
display(arr,m);
exhibit(arr,m);
}
Print1(int b[ ][2],int l,int p)
{
int i,j;
printf("Receiving as two dimension array \n");

Sikkim Manipal University B2074 Page No.: 212


Principles of C Programming Unit 10

for(i=0;i<l;i++)
{
printf("%d %d \n",b[i][0],b[i][1]);
}
}
Print2(int *b,int l,int p)
{
int i,j;
printf("Receiving as a pointer \n");
for(i=0;i<l;i++)
{
printf("%d %d \n",*(b+i*2+0),*(b+i*2+1));
}
}
Print3 (int(*b)[2],int l)
{
int i,j,*p;
printf("Receiving as a one dimension pointer array \n");
for(i=0;i<l;i++)
{
p=(int*)b;
printf("%d %d \n",*(p),*(p+1));
b++;
}
}
Print4 (int (*b)[5][2],int l)
{

int i,j;
printf("Receiving as two dimension pointer array : \n");
for(i=0;i<l;i++)
{
printf("%d %d \n",(*b)[i][0],(*b)[i][1]);
}
}

Sikkim Manipal University B2074 Page No.: 213


Principles of C Programming Unit 10

The functions, print1, print1, print3 and print4, are used to demonstrate how
the arrays are passed as arguments. The function call is the same but the
way the arguments are received in the function definition is different. Print1
gets it as an array, print2 gets it as a pointer, and print3 gets it as a one
dimensional pointer array and print4 as a two dimensional pointer array. All
the functions do exactly the same thing that is to print out the elements of
the array. Note the different ways the elements are accessed inside each of
these functions.
In the function print2 the two-dimensional array is received as pointer. On
incrementing this pointer we can access each of the elements of the two-
dimensional array. The elements of the array are read row by row.
In the function Print3 the two-dimensional array is received as a one-
dimensional pointer array b. By default, this pointer array, which had the
same number of elements as the number of columns in two-dimensional
arrays, is pointing to the first row of the two-dimensional array. To access
these elements we now need another pointer, which is defined here as p.
We then make the assignment p=(int*)b inside this function and read the
two elements of the first row. When we increment b by b++ we go to the
next row and so on.
In the case of function Print4 each element of the two-dimensional array of
pointers is pointing to the corresponding element of array. Please note the
use of parenthesis to read the elements of this array of pointers.
10.3.2 Passing String
As we can pass other kinds of arrays to functions, we can do so with strings.
Example 10.2: Here is the definition of a function that prints a string and a
call to that function:
void print_string(char print_str [])
{
printf("String : %s\n", print_str);
}
int main(void)
{
char str[] = "test string";
print_string (str);
}

Sikkim Manipal University B2074 Page No.: 214


Principles of C Programming Unit 10

str is a character array, and the function print_string () expects a character


array. However, if we have a pointer to the character array label, as in:
char *str1 = str;
then we can also pass the pointer to the function, as in:
print_string (str1);
The results are the same, because when we declare an array as the
parameter to a function, we really just get a pointer. And we know that
arrays are always automatically passed by reference. So,print_string ()
could have been written in two ways:
void print_string (char print_str[])
{
printf("String : %s\n", print_str);
}
OR
void print_string (char * print_str)
{
printf("String : %s\n", print_str);
}
There is no difference because in both cases the parameter is really a
pointer.
Self-Assessment Questions
3. To pass an entire array to the function, _________ is used as an
argument to a function.
4. Multidimensional arrays cannot be passed to the function. (True/False)

10.4 Storage Classes and Visibility


There are two ways to categorize variables: by data type, and by storage
class. Data type refers to the type of information represented by a variable,
for example, integer number, floating-point number, character and so on.
Storage class refers to the persistence of a variable and its scope within the
program, that is, the portion of the program over which the variable is
recognized.
The following types of storage-class specifications in C are discussed in this
unit: global, automatic or local, static, and extern. The exact procedure for
establishing a storage class for a variable depends upon the particular

Sikkim Manipal University B2074 Page No.: 215


Principles of C Programming Unit 10

storage class, and the manner in which the program is organized, (that is.
single file vs. multiple file).
The visibility of a variable determines the program’s ability to access a
variable that is determining “accessibility” of the variable declared from the
rest of program. It is the result of hiding a variable in outer scopes. Visibility
provides security for our data used in a program. We can arrange that a
variable is visible only within one part of one function, or in one function, or
in one source file, or anywhere in the program.
The question that arises is why would we want to limit the visibility of a
variable? For maximum flexibility, would not it be handy if all variables were
potentially visible everywhere? As it happens, that arrangement would be
too flexible: everywhere in a program, we would have to keep track of the
names of all the variables declared anywhere else in the program, so that
we do not accidentally re-use one. Assuming a variable had the wrong
value, we would have to search the entire program for the bug, because any
statement in the entire program could potentially have modified that
variable. We would constantly be stepping all over a common variable
name like i in two parts of our program, and having one snippet of code
accidentally overwrite the values being used by another part of the code.
Self-Assessment Questions
5. The visibility of a variable determines accessibility of variable in rest of
the program. (True/False)
6. __________ class refers to the persistence of a variable and its scope
within the program, that is, the portion of the program over which the
variable is recognized.
7. Visibility provides security for data used in a program. (True/False)

10.5 Automatic or Local Variables


A variable declared within the braces {} of a function is visible only within
that function; variables declared within functions are called local variables.
Their scope is confined to that function. We can use the keyword auto to
declare automatic variables, but, however it is optional. If another function
somewhere else declares a local variable with the same name, it is a
different variable entirely, and the two do not clash with each other. If an

Sikkim Manipal University B2074 Page No.: 216


Principles of C Programming Unit 10

automatic variable is not initialized in some manner, its initial value will be
unpredictable and contains some garbage value.
Program 10.4: Program to find factorial of a number.
#include<stdio.h>
main()
{
auto int n; /* Here the keyword auto is optional */
long int fact(int);
printf(“read the integer n:”);
scanf(“%d”, &n);
printf(“\nn!=%ld”, fact(n) );
}
long int fact(auto int n) /* n is local to the function fact() and auto is optional*/
{
auto int i; /* Here the keyword auto is optional */
auto long int factorial=1; /* Here the keyword auto is optional */
while(n>0)
{
factorial=factorial*n;
n=n-1;
}
return factorial;
}
An automatic variable does not retain its value once control is transferred
out of its defining function. Therefore, any value assigned to an automatic
variable within a function will be lost once the function is exited.
Self-Assessment Questions
8. The scope of ________ variable is in the function in which it is declared
in which it is declared.
9. Does an automatic variable retain its value once control is transferred
out of its defining function? (Yes/No)
10. The key word auto is must in the declaration of automatic variables.
(True/False)

Sikkim Manipal University B2074 Page No.: 217


Principles of C Programming Unit 10

10.6 Global Variables


A variable declared outside of any function is a global variable, and it is
potentially visible anywhere within the program. We use global variables
when we do want to use the variable in any part of the program. The global
variables are less secure than the automatic variables in a program, as any
function can modify global variable. When we declare a global variable, we
will usually give it a longer, more descriptive name (not something generic
like i). The values stored in global variables persist, for as long as the
program persist. (Of course, the values can in general still be overwritten, so
they do not actually persist forever.)
Program 10.5: Program to find average length of several lines of text
#include<stdio.h>
/* Declare global variables outside of all the functions*/
int sum=0; /* total number of characters */
int lines=0; /* total number of lines */
main()
{
int n; /* number of characters in given line */
float avg; /* average number of characters per line */
void linecount(void); /* function declaraction */
float cal_avg(void);
printf(“Enter the text below:\n”);
while((n=linecount())>0) {
sum+=n;
++lines;
}
avg=cal_avg();
printf(“\nAverage number of characters per line: %5.2f”, avg);
}
void linecount(void)
{
/* read a line of text and count the number of characters */
char line[80];
int count=0;
while((line[count]=getchar())!=’\n’)
++count;

Sikkim Manipal University B2074 Page No.: 218


Principles of C Programming Unit 10

return count;
}
float cal_avg(void)
{
/* compute average and return*/
return (float)sum/lines;
}

In the program 10.5, the variables sum and lines are globally declared and
hence they could be used in both the functions main() and cal_avg().
Self Assessment Questions
11. The variables declared in the main() function are the global variables.
(True/False)
12. The global variables are more secured than the automatic variables in
a program. (True/False)

10.7 Static Variables


The keyword static can be used in two major contexts: inside a function and
in front of a global variable inside a file making up a multi file program.
Static variables are defined within individual functions and therefore have
the same scope as automatic variables, means they are local to the
functions in which they are declared. Unlike automatic variables, however,
static variables retain their values throughout the life of the program. As a
result, if a function is exited and then reentered later, the static variables
defined within that function will retain their previous values. This feature
allows functions to retain information permanently throughout the execution
of a program. Static variables can be utilized within the function in the same
manner as other variables. They cannot be accessed outside of their
defining function.
In order to declare a static variable the keyword static is used as shown
below:
static int count;
We can define automatic or static variables having the same name as global
variables. In such situations the local variables will take precedence over
the global variables, though the values of global variables will be unaffected
by any manipulation of the local variables.
Sikkim Manipal University B2074 Page No.: 219
Principles of C Programming Unit 10

Initial values can be included in static variable declaration. The rules


associated with the initialization remain same as the initialization of
automatic or global variables. They are:
1. The initial values must be constants, not expressions.
2. The initial values are assigned to their respective variables at the
beginning of the program execution. The variables retain these values
throughout the life of the program, unless different values are assigned
during computation.
3. Zeros will be assigned to all static variables whose declarations do not
include explicit initial values.
Program 10.6: Program to generate Fibonacci numbers.

#include<stdio.h>
main()
{
int count, n;
long int fib(int);
printf(“\n How many Fibonacci numbers?”);
scanf(“%d\n”, &n);
for(count=1;count<=n;count++)
{
printf(“\ni=%d F=%ld”, count, fib(count));
}

long int fib(int count)


{
/* calculate a Fibonacci number using the formula
if i=1, F=0; if i=2, F=1, and F=F1+F2 for i>=3 */
static long int f1=0, f2=1; /* declaration of static variables */
long int f;
if (count==1)
f=0;
else if (count==2)
f=1;
else
f=f1+f2;
f2=f1;

Sikkim Manipal University B2074 Page No.: 220


Principles of C Programming Unit 10

f1=f; /* f1 and f2 retain their values between different calls of the


function*/
return f;
}

In fib function, variable f1 and f2 variable are declared as static variable


hence variables f1 and f2 retain these values throughout the life of the
program. Note that we can access variables f1 and f2 only in the function
fib.

Self-Assessment Questions
13. The scope of static variables and automatic variables is the same.
(True/False)
14. ____________ variables defined within individual functions retain their
values throughout the life of the program and has same scope as
automatic variables.
15. By default, a static variable is initialized to _______.

10.8 External Variables


We can write various functions into several source files, for easier
maintenance. When, several source files are combined into one program
the compiler must have a way of correlating the variables which might be
used to communicate between the several source files. Furthermore, if a
variable is going to be useful for communication, there must be exactly one
of it: we would not want one function in one source file to store a value in
one variable named externvar, and then have another function in another
source file read from a different variable named externvar. Therefore, a
variable should have exactly one defining instance, in one place in one
source file. If the same variable is to be used anywhere else (that is in some
other source file or files), the variable is declared in those other file(s) with
an external declaration, which is not a defining instance. The external
declaration says the compiler that the variable will be used in this source file
but defined in some other source file. Thus, the compiler does not allocate
space for that variable with this source file.
Global variable declared in one file, but used by functions from another then
variable is called an external variable in these functions and must be

Sikkim Manipal University B2074 Page No.: 221


Principles of C Programming Unit 10

declared with extern keyword that is to use a variable, which is defined other
source files; We precede variable with the keyword extern:
extern int j;
Program 10.7: Program to illustrate the concept of external variables.
Type and save the following program in a source file called
externvariables.h
int principle=10000;
float rate=5.5;
int time=2;
float interest;

Type and save the following program in a separate source file called
demoexternvar.c
#include<stdio.h>
#include “externvariables.h” /* the source file where the external variables
are defined should be included here.*/
main()
{
/* external declarations of the variables which are defined in
externvariables.h */
extern int principle;
extern float rate;
extern int time;
extern float interest;
/*compute interest*/
interest= principle*rate*time/100.0;
printf(“Interest=%f\n”, interest);
}

Compile demoexternvar.c and execute the program.


The concept of external storage class can be extended to functions as well.
A source file can access a function defined in any other source file provided
the source file is included within the source file where we access that
function.

Sikkim Manipal University B2074 Page No.: 222


Principles of C Programming Unit 10

Program 10.8: Program to illustrate the concept of external functions.


Type and save the following program in a file externfunction.h
void output(void)
{
printf(“ Programming in C is fun !\n”);
return;
}

Type and save the following program in a separate source file called
demoexternfun.c
#include<stdio.h>
#include “ externfunction.h”
extern void output(void);
main()
{
output();
}

Compile and execute the above program and observe the result.
External variables and functions are visible over the entire (possibly multi-
file) program; they have external scope (also called program scope). This
means that a function may be called from any function in the program, and
an external variable may be accessed or changed by any function.
However, it is necessary to first declare a variable or function in each file
before it is used.
However, the keyword extern is optional in some C compilers. If, a global
variable is defined with the keyword static then it is visible only within the file
scope in which they are defined. This means that the variable would not be
available to any function that is defined in a file other than the file in which
the variable is defined.
Self-Assessment Questions
16. The main purpose of using ________variables is to access the same
variable in different source files.
17. Compiler does not allocate memory for an external variable where it is
accessed. (True/False)

Sikkim Manipal University B2074 Page No.: 223


Principles of C Programming Unit 10

18. Global variables and external variables have the same scope.
(True/False)
Example 10.3: Here is an example demonstrating declaration of variables
with different scopes.
int globalvar = 1;
extern int anotherglobalvar;
static int privatevar;
f()
{
int localvar;
int localvar2 = 2;
static int persistentvar;
}

Here we have six variables, three declared outside and three declared
inside of the function f().
globalvar is a global variable. The declaration we see is its defining
instance (it happens also to include an initial value). Globalvar can be used
anywhere in this source file, and it could be used in other source files, too
(as long as corresponding external declarations are issued in those other
source files).
anotherglobalvar is a second global variable. It is not defined here; the
defining instance for it (and its initialization) is somewhere else.
privatevar is a “private'' global variable. It can be used anywhere within this
source file, but functions in other source files cannot access it, even if they
try to issue external declarations for it. (If other source files try to declare a
global variable called ‘’privatevar'', they will get their own; they will not be
sharing this one.) Since it has static duration and receives no explicit
initialization, privatevar will be initialized to 0.
localvar is a local variable within the function f(). It can be accessed only
within the function f(). (If any other part of the program declares a variable
named “localvar”, that variable will be distinct from the one we are looking
at here). localvar is conceptually “created” each time f() is called, and
disappears when f() returns. Any value which was stored in localvar last
time f() was running will be lost and will not be available next time f() is
Sikkim Manipal University B2074 Page No.: 224
Principles of C Programming Unit 10

called. Further, since it has no explicit initializer, the value of localvar will in
general be garbage each time f() is called.
localvar2 is also local, and everything that we said about localvar applies
to it, except that since its declaration includes an explicit initializer, it will be
initialized to 2 each time f() is called.
Finally, persistentvar is again local to f(), but it does maintain its value
between calls to f(). It has static duration but no explicit initializer, so its
initial value will be 0.
Program 10.9: Program to illustrate the hiding of variables in blocks.
/* hiding.c -- variables in blocks */
#include <stdio.h>
int main()
{
int x = 30;
printf("x in outer block: %d\n", x);
{
int x = 77; /* new x, hides first x */
printf("x in inner block: %d\n", x);
}
printf("x in outer block: %d\n", x);
while (x++ < 33)
{
int x = 100; /* new x, hides first x */
x++;
printf("x in while loop: %d\n", x);
}
return 0;
}
OUTPUT:
x in outer block: 30
x in inner block: 77
x in outer block: 30
x in while loop: 101
x in while loop: 101
x in while loop: 101

Sikkim Manipal University B2074 Page No.: 225


Principles of C Programming Unit 10

Observe the output of the program, variable x is defined in three places. The
local variables instance of x declared within a block will take precedence
over the x variables declared outside of the block.

10.9 Summary
Let us recapitulate important points discussed in this unit:
 In C, functions exchange information by means of formal parameters,
actual parameters and return values.
 In passing parameter by value mechanism, function receives the actual
values of arguments and assigned to corresponding formal parameters.
 In passing parameter by reference mechanism, we are passing
addresses of the variables to a function instead of actual value of
parameter.
 We can pass an un-sized array as a single argument to a function. We
can also pass an array to a function through a pointer. The pointer
should hold the start address of the array.
 Variables are channels of communication within a program. Storage
class refers to the persistence of a variable and its scope within the
program, that is, the portion of the program over which the variable is
recognized.
 The scope of a local or automatic variable is confined to the function
where it is defined.
 A global variable is potentially visible anywhere within the program in
which it is defined.
 Static variables retain their values throughout the life of the program. As
a result, if a function is exited and then reentered later, the static
variables defined within that function will retain their previous values.
 The external variable declaration says the compiler that the global
variable will be used in this source file but defined in some other source
file.

10.10 Terminal Questions


1. List some storage classes available in C.
2. What is the significance of external declaration?
3. Justify that variables are channels of communication in a program.

Sikkim Manipal University B2074 Page No.: 226


Principles of C Programming Unit 10

4. Write difference between parameter passing by value and reference


mechanism.
5. Explain passing of two dimension arrays to function.

10.11 Answers
Self-Assessment Questions
1. Value
2. Reference
3. Array Name
4. False
5. True
6. Storage
7. True
8. Automatic
9. No
10. False
11. False
12. False
13. True
14. Static
15. Zero
16. External
17. True
18. False
Terminal Questions
1. automatic, global, static, extern. (Refer section 10.4 for detail)
2. The external declaration says the compiler that the variable will be used
in this source file but defined in some other source file. (Refer section
10.8 for detail)
3. We set a variable to a value at one point in a program, and at another
point (or points) we read the value out again. Thus, the transfer of
information from one point of the program to another is nothing but the
communication. (Refer section 10.2 for detail)
4. Using passing parameter by value mechanism, function receives the
actual values of argument and assigned to corresponding formal
parameters. Whereas in passing parameter by reference mechanism,
Sikkim Manipal University B2074 Page No.: 227
Principles of C Programming Unit 10

we are passing addresses of the variables to a function instead of


actual value of argument. (Refer section 10.2 for detail)
5. We pass two dimension arrays in four ways as shown below:
1. An array to an array a[m][n] to b[m][n]
2. An array to a pointer a[m][n] to * p
3. An array to a one dimensional pointer array a[m][n] to ( *q )[n]
4. An array to a two dimensional pointer array a[m][n] to ( *q )[m][n]
(Refer section 10.3.1 for detail)

10.12 Exercises
1. Distinguish between the following
i. Global and local variables
ii. Automatic and static variables
iii. Global and extern variables
2. Write a program to count the number of times a function is called using
static variables.
3. Write a function prime that returns 1 if its argument is a prime number
and returns zero Otherwise.
4. Write a function that will round a floating point number to an indicated
decimal place. For example, the number 12.456 would yield the value
12. 46 when it is rounded off to two decimal places.
5. Write a program to illustrate the concept of extern variables.
6. Given a two-dimensional character array, str, that is initialized as char
str[2][15] = { “We know what,”, “C is powerful.” }; write a program to pass
the start address of str to a function that prints out the content of the
character array.

Reference and further reading:


1. Balaguruswami , “Programming In Ansi C 5E” Tata McGraw-Hill
2. Ajay Mittal (2010), “Programming In C: A Practical Approach”, Published
by Pearson education.

Sikkim Manipal University B2074 Page No.: 228

You might also like