BIT104 SLM Library - SLM - Unit 10
BIT104 SLM Library - SLM - Unit 10
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
}
Output:
Before a = 10 b = 20
After a = 20 b = 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];
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");
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]);
}
}
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);
}
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)
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)
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)
#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));
}
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 _______.
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);
}
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)
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
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.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
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.