c programming language functions notes
TRANSCRIPT
-
7/29/2019 C programming language functions notes
1/35
-
7/29/2019 C programming language functions notes
2/35
3.The length of the source program can be reduced by using functions at
appropriate places.
4. It makes debugging easy : It becomes uncomplicated to locate and
separate a faulty function for further study.
5.A function may be used later by many other programs this means that
a c programmer can use function written by others, instead of starting
over from scratch.
6.Saves memory and time.
3.2 What is modular programming? What are the characteristics of
to-down modular approach?
Modular programming is a strategy applied to the design and development of
software systems. It is defined as organizing a large program into small,
independent program segments called modules that are separately named
and individually callable program units. These modules are integrated to
become a software system that satisfies the system requirements. It is
basically a divide-and-conquer approach to problem solving.
Fig 3.1: Top-down modular programming using functions
In the above fig 3.1, the main function is divided into 3 sub-functions
function1, function2, function3 and then the sub-function is again divided
into tow modules A and B.
Characteristics of module programming:
-
7/29/2019 C programming language functions notes
3/35
1. Each module should do only one thing.
2. A module can be called by only one higher module.
3. All modules are designed as single-entry, single-exit systems using control
structures.
4. Communication between modules is allowed only by a calling module.
5. No communication can take place between modules that do not have
calling-called relationship.
3.3 What are the similarities between variables and functions in C?
1. Both function names and variable names are considered as identifiers and
therefore they must adhere to the rules for identifiers.
2. Like variables, functions have types (such as int) associated with them.
3. Like variables, function names and their types must be declared and
defined before they are used in a program.
3.4 What are the elements of user-defined functions? Explain.
In order to make use of a function, we need to establish three elements that
are related to functions.
1. Function declaration.
2. Function call.
3. Function definition.
Function declaration: Initially we have to declare the function before using it.
Similar to how we declare a variable before using it. But the difference is a
variable is declared inside the main() where as function is declared outside
the main().
Function Call: In order to use the function, we need to invoke it by making a
function call. The function which is calling a sub-function is called calling
function and the function which is being called is called as called function.
-
7/29/2019 C programming language functions notes
4/35
Function definition: The task performed by the sub-function is written in this
section i.e, actual program for the sub-function depending on the
requirements is written here.
The various elements of a function are shown in the example given below.
Example: /*To print a simple message */
#include
void printline(void); // function declaration
void main()
{
printline(); // function calling
getch();
}
void printline(void) // function definition
{
printf(Welcome to C functions \n); //functions executable statements
}
Output: Welcome to C functions
Explanation:
Initially the function is decalred. From the main(), the sub-function named
printline is called. Here, main() is the calling function and printline() is the
called function. When the printline() is called from the main function, the
control goes to the printline() where the message Welcome to C functions
gets printed.
1. Function declaration or Function prototype
Like variables, all functions in a C program must be declared, before being
invoked. A function declaration or prototype consists of four parts,
-
7/29/2019 C programming language functions notes
5/35
1. Function type (return type)
2. Function name
3. Parameter list
4. Terminating semicolon.
Syntax: Function_type function_name (parameter_list);
Eg: void printline (void);
2. Function Call
A function can be called by simply using the function name followed by a list
of actual parameters, if any, enclosed in parenthesis.
Eg: printline(); (is a function call to the function whose name is printline
and sends no arguments)
When the compiler encounters a function call, the control is transferred to
the function. The function is then executed line by line and a value is
returned (if any) when the return statement is encountered. Thus the
control is transferred back to the main (or calling) function. The compiler
continues executing the next statements in the calling function.
3. Function definition
A general form of a C function definition looks like this:
function_type function_name (Argument1, Argument2, Argument3)
{
Local variable declarations;
executable statement1; executable statement2;
.
.
return statement;
}
-
7/29/2019 C programming language functions notes
6/35
A function definition, also known as function implementation consists of six
elements,
1. function name
2. function type
3. list of parameters
4. local variable declarations
5. function executable statements and
6. a return statements
All the six elements are grouped into two parts, namely,
Function header (First three elements) and
Function body (second three elements)
Function Header:
The function header consists of three parts: the function type (also known
as return type), the function name and the formal parameter list. A semicolon is
not used at the end of the function header.
Name and type: The function type specifies the type of value (like float or double)
that the function is expected to return to the program calling the function. If the
return type is not explicitly specified, then default return type is int. If the function
is not returning anything, then we need to specify the return type or function type
as void. The value returned is the output produced by the function.
The function name is any valid identifier and therefore must follow the
same rules as that of variable name declaration. However, we should not give
the library names as function names.
2. Formal parameter list: The parameter list or argument list declares the
variables that will receive the data sent by the calling function. They serve as
input data to the function to carry out the specific task. Since, they represent the
-
7/29/2019 C programming language functions notes
7/35
replica of the actual parameters sent from the calling function, they are often
referred as formal parameters.
Eg: int add(int x, int y)
float mul(int a,int b,int c)
void printline()
These are examples for function header.
Function body: The function body contains the declarations and statements
necessary for performing the required task. The body enclosed in braces,
consists of three parts given in the following order.
1. Local declarations that specify the variables needed by the function.
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 like the example given
above (in the printline function), we can omit the return statement. In such cases,
closing brace of the function acts as return statement so that whenever the
closing brace is encountered by the compiler, the control is returned back to the
calling function.
Eg: int add(int x,int y) //function header
{ int sum; //local variable declaration
sum=x+y; //executable statement
return(sum); //return statement
}
3.4 What are the various rules for function declaration?
1. The parameter list must be separated by the commas.
2. Use of parameter names in the declaration is optional.
3. The parameter names do not need to be the same in the prototype
declaration and the function definition.
4. The types must match the types of parameters in the function declaration,
in number and order.
-
7/29/2019 C programming language functions notes
8/35
5. If the function has no formal parameters, the list is written as (void).
6. The return type is optional, when the function returns int type data.
7. The return type should be void if no value is returned.
8. When the declared types do not match with the type in the function
definition, compiler will produce an error.
3.5 Write a short note on return values and their types.
The value evaluated by the function is returned back to the calling function
through return statement. While it is possible to pass to the called function
any number of values, the called function can only return one value per call,
at the most.
The return statement can take any one of the following forms:
return;
Or
return(expression);
The plain return value does not return any value, it acts much as the closing
brace of the function. When the return is encountered, the control is
immediately passed back to the calling function.
Eg: 1. if(x>y)
return; //simple return statement
2. int mul(int x,int y)
{ int p ;
p=x*y ;
return(p) ; //returns a value
}
3. if(x>0)
return(0); //returns either 0 or 1 depending on the condition
else
return(1);
A function may have one or more return statements, but at a given point of
time, a called function can return only one value based on the condition
encountered.
-
7/29/2019 C programming language functions notes
9/35
The second form of return statement with an expression returns the value of
the expression as shown below.
return(x*y);
3.6 What are actual and formal arguments?
The parameters used in prototype and function definition are called formal
parameters and those used in function calls are called actual parameters.
Actual arguments used in the calling statement may be simple constants,
variables or expressions.
The formal and actual parameters must match exactly in type, order and
number. Their names however, do not need to match.
3.7 What are the various categories of function? Explain with
examples.
A function, depending on whether arguments are present or not and whether
a value is returned or not, may belong to any one of the following categories:
1.Functions with no arguments and no return values.
2.Functions with arguments and no return values.
3.Functions with arguments and return values.
4.Functions that return multiple values.
5.Functions with no arguments and return values.
1. No arguments and no return values:
It is one of the simplest types of function in C. A function without any
arguments means you cannot pass data to the called function. Similarly,function with no return type does not pass back data to the calling function.
-
7/29/2019 C programming language functions notes
10/35
fig 3.2 No data communication between functions
The above block diagram shows the communication between the calling and
called functions of category1. The dark lines indicate the communication
(control passing) between the two functions where as dotted lines indicate
that there is no data is being transferred between two functions.
Example:
/*To print a simple message */
#include
void printline(void); // function declaration
void main()
{
printline(); // function calling
getch();
}
void printline(void) // function definition
{
printf(Welcome to C functions \n); //functions executable statements
}
Output: Welcome to C functions
-
7/29/2019 C programming language functions notes
11/35
Explanation:
Initially the function is declared. From the main(), the sub-function named
printline is called. Here, main() is the calling function and printline() is thecalled function. When the printline() is called from the main function, the
control goes to the printline() where the message Welcome to C functions
gets printed.
2. Functions With arguments and no return values:
A C function with arguments can perform much better than previous function
type. This type of function can accept data from calling function. In other
words, you send data to the called function from calling function but you
cannot send result data back to the calling function. Rather, it displays the
result on the terminal.
Fig 3.3. One way data communication
The block diagram of category 2 (in fig 3.3) represents one way data
communication because only data is passed from calling function to called
function and no data is returning back to the calling function. The control is
being transferred to and fro between the two functions.
Example:
-
7/29/2019 C programming language functions notes
12/35
/*Program to add two intergers using category 2*/
#include
void add(int x, int y); //function declaration
void main()
{
clrscr();
add(30,15); //function call
add(6,4); //function call
getch();
}
void add(int x, int y) //function definition
{
int result;
result = x+y;
printf("Sum of %d and %d is %d.\n\n",x,y,result);
}
Output: Sum of 30 and 15 is 45
Sum of 6 and 4 is 10
Explanation:
This program consists of a function named add. This function add() takes two
values as arguments, add those two values and stores the result in another
variable result and then prints the result as shown above.
Above example is a small and simple program so it does not appear great to
use function. But assume a function consist 20 30 or more lines then it
would not be wise to write same block of code wherever we need them. In
such cases functions come handy, declare once, use wherever you want.
The sub-function is called twice by the calling function with different values
and each function call gives different output. So, we can control functions
output by providing different integer parameters which was not possible in
function type 1. This is the difference between function with no argument
and function with argument.
-
7/29/2019 C programming language functions notes
13/35
3. Functions with arguments and return value.
This type of function can send arguments (data) from the calling function to
the called function and wait for the result to be returned back from the called
function back to the calling function. And this type of function is mostly used
in programming world because it can do two way communications; it can
accept data as arguments as well as can send back data as return value. The
data returned by the function can be used later in our program for further
calculations.
Fig 3.4 Two-way data communication between functions
The block diagram of function with arguments and with return values is
shown in fig 3.4. The dark lines indicate the transfer of both data and
control between the calling and called functions.
Example:
#include
int add(int,int); //function prototype
void main()
{
-
7/29/2019 C programming language functions notes
14/35
int z;
z = add(52,48); // function call
printf("Result= %d.\n\n",add(30,55)); // function call
printf("Result= %d.\n\n",z);
getch();
}
int add(int x, int y)
{
int result;
result = x+y;
return(result); //result is being returned back to calling function
}
Output: Result=85
Result=100
Explanation: The main function sends two integer values to the add
function. The add() adds two values and sends back the result to the calling
function. Later result is printed on the terminal. (Terminal is an output device
such as monitor or printer).
4. Functions with no arguments but returns value.
We may need a function which does not take any argument but only returns
values to the calling function then this type of function is useful. The best
example of this type of function is getchar() library function which is
declared in the header file stdio.h. We can declare a similar library function
of our own as shown in tht example below.
-
7/29/2019 C programming language functions notes
15/35
Example:
#include
int get_number(void); //function prototype
void main()
{ int m=get_number(); //function call
printf(\n %d,m);
}
int get_number(void) //function definition
{ int num;
Printf(Enter a number:);
scanf(%d,&num);
return(num);
}
Output: Enter a number:10
10
Explanation:
-
7/29/2019 C programming language functions notes
16/35
In this program the sub-function takes one integer as input from keyboard
and sends back to the calling function. No data is being passed from the
calling function but it is returning a value back to the calling function.
5. Functions that return multiple values:A return statement can return only one value. But there might be situations
where we want to send back more than one value.
We have used arguments to send values to the called function, in the same
way we can also use arguments to send back information to the calling
function. The arguments that are used to send back data are called Output
Parameters.
The mechanism of sending back information through arguments is achieved
using what are known address operator (&) and indirection operator(*) . The
concept of pointers is used here. Let us see the example below.
Example:
#include
void main()
{
int a=20, b=11, p,q;
calc(a,b,&p,&q);
printf("Sum = %d, Sub = %d",p,q);
getch();
}
void calc(int x, int y, int *add, int *sub)
{
*add = x+y;
*sub = x-y;
}
Output: Sum = 31, Sub = 9
Explanation: We can get memory address of any variable by simply
placingn & before variable name. In the same way, we can get the value
-
7/29/2019 C programming language functions notes
17/35
stored at specific memory location by using * just before the memory
address. Pointer can only store address of the value rather than value but
when we add * to pointer variable then we can store value at that address.
In the above program, the function call consists of four arguments, first two
arguments a and b are input arguments and last two arguments are integer
pointers which works as output parameters. When we call calc() function
then the following assignments occurs. Value of variable a is assigned to x,
value of b is assigned as y, addresses of p and q are assigned to add
and sub respectively. In the sub-function, we are adding and subtracting
values and storing the result at their respectively memory locations. i.e the
memory locations of p and q. So we can print the values using p and q
variables in the main().
3.8 What is call by value and call by reference? Explain.
(Or)
What is pass by value and pass by address(or pass by pointers)?
1. Pass by value
Values of actual parameters are copied to the variables in the
parameter list of the called function. The 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.
2. Pass by address or Pass by reference or Pass of pointers
The memory addresses of the variables rather than the copies of
values are sent to the called function. Here, the called function directly works
on the data in the calling function and the changed values are available in
the calling function for its use. Therefore a possible change on the data at the
referenced address changes the original value of the argument.
-
7/29/2019 C programming language functions notes
18/35
Pass by pointers method is also called as pass by address or pass by
reference. It is often used when manipulating arrays and strings. This
method is also used when we require multiple return values.
3.9 What are the rules for pass by pointers?
1) The type of actual and formal arguments must be same.
2) The actual arguments must be the address of variables that are local
to the calling function.
3) The formal arguments in the function header must be prefixed by the
indirection operator (*).
4) In the function 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 *.
3.10 Write a short note on nesting of functions.
C permits nesting of functions freely. Nesting of functions is main()
can call function1(), which calls function2(), which calls function3() and so
on. There is no limit in C to how deeply functions can be nested.
For example, a statement like
p=mul(mul(5,2),3); is valid.
This represents two sequential function calls. The inner function call is
evaluated first and the returned value is again used as an actual
argument in the outer function call. So, in the above example, if the first
call returns multiplication of two integers i.e, 5x2=10 as output of inner
call. Then the function call transforms to mul(10,3). Therefore, one more
time, the mul() is being called. Hence the final output returned is 30.
-
7/29/2019 C programming language functions notes
19/35
Note that the nesting of functions does not mean defining one function
within another. This is illegal. Nesting of functions mean calling a function
from another function.
3.11 What is recursion or recursive call? What is the need or
advantage of recursive call? Explain with an example.
(Or)
What is recursion or recursive call? Mention a few points where
we use the recursive call.
Recursion is a technique of calling a function by itself. For example,
main()
{ printf(Recursion call \n);
main();
}
Output: Recursion call
Recursion call
Recursion call
In the above example, the main() is calling itself. Execution has to be
terminated abruptly; otherwise the execution will continue indefinitely.
Recursive function can be effectively used to solve problems where solution
is expressed in terms of successively applying the same solution to subsets
of the problem. When we write recursive functions, we must have an if
-
7/29/2019 C programming language functions notes
20/35
statement somewhere to force the function to return without the recursive
call being executed. Otherwise, the function will never return.
3.12 Write a program to calculate factorial of a given number using
recursive technique.
Factorial of n = n(n-1)(n-2)......1.
/*Factorial of a given number using recursion technique*/
#include
long int fact(int n); //function declaration
void main()
{ int n;
printf(Enter a value to calculate its factorial: \n);
scanf(%d,&n);
printf(\n The factorial of %d is %ld, n, fact(n)); //function call
getch();
}
long int fact(int n) //function definition
{ long int f;
if(n==1)
return(1);
else
-
7/29/2019 C programming language functions notes
21/35
f=n*fact(n-1); //recursive call
return(f);
}
Output: Enter a value to calculate its factorial: 3
The factorial of 3 is 6
The recursive call is evaluated by the statement, f= n* fact(n-1);
1. Assume n=3, since n!=1, then f= 3 * fact(2);
2. So now fact() is calling itself sending n=2, so from this call we get f=2 *
fact(1);
3. Once again fact() is called with n=1. This time function returns 1 because
n==1.
The sequence of operations is simplified as given below.
f= 3 * fact(2)
=2 * fact(1)
=3 * 2 * 1
=6
3.13 How can you pass variable number of arguments to a function?
-
7/29/2019 C programming language functions notes
22/35
Some functions have a variable number of arguments and data types cannot
be known at the compile time.
Example: printf, scanf functions.
With the help of ellipsis symbol(), we can handle such functions.
Exapmle: double area(float d,);
Both the function declaration and definition should use ellipsis to indicate that
the arguments are arbitrary both in number and type.
3.14 How do we pass arrays to function?
Like the values of simple variables, it is also possible to pass the values of an
array to a function.
To pass a 1-D array to a called function, it is sufficient to list the name of the
array without any subscripts and its size as arguments.
Example for function call: sum(a,n);
Where, a is the name of the array and n is array size. Suppose sum is a
function name. The function call above will pass the whole array a to the
called function.
The function header might look like:
Function header: float sum(float a[],int n)
The function sum is defined to take two arguments, the array name and thesize of the array to specify the size of the array. The declaration of the formal
argument array a is made as follows: float a[];
The pair of brackets informs the compiler that the argument a is an array of
numbers. It is not necessary to specify the size of the array size.
-
7/29/2019 C programming language functions notes
23/35
Example program: The following Program finds out the sum of the
elements in a given array where the array is being passed to a function.
float sum(float a[],int n); // function declaration
main()
{ float a[5] = {1,2,3,4,5}; //array declaration and initialization
float total;
total = sum(a,n); //function call
printf("sum=%f \n",total);
getch();
}
float sum(float a[],int n) //function definition
{ int i;
float sum=0;
for(i=0;i
-
7/29/2019 C programming language functions notes
24/35
Output: Sum = 15
In C, the name of the array represents the address of its first element. By
passing the array name, we are in fact, passing the address of the array to
the called function. The array in the called function now refers to the same
array (original array) stored in the memory. Therefore, any changes in the
array in the called function can be referred to the original array.
Passing addresses of parameters to the functions is referred to as pass by
address or pass by pointers. So passing array to function comes under pass
by address.
3.15 Explain how passing array to function is related to the concept
of pass by address.
In C, the name of the array represents the address of its first element. By
passing the array name, we are in fact, passing the address of the array to
the called function. The array in the called function now refers to the same
array (original array) stored in the memory. Therefore, any changes in the
array in the called function can be referred to the original array.
Passing addresses of parameters to the functions is referred to as pass by
address or pass by pointers. So passing array to function comes under pass
by address.
Let us see an example of sorting given elements of an array to illustrate the
concept of pass by address.
Program: To arrange the elements of an array in ascending order
/*sorting using functions.....Ascending order*/
#include
float ascend(float a[],int n); //function declaration
-
7/29/2019 C programming language functions notes
25/35
main()
{ float a[5]={40,50,20,10,100};
int i;
ascend(a,n); //function call
for(i=0;i
-
7/29/2019 C programming language functions notes
26/35
}
}
}
}
Output: 10 20 40 50 100
So, what ever the changes we are making to the array in the sub-function is
being reflected in the original array from where it is passed. Thus we have
arranged the elements of an array in ascending order.
3.16 What are the three rules to pass an array to a function?
The three rules to pass an array to a function are
1. The function must be called by passing only the name of the array.
2. In the function declaration, the formal parameters must be of array
type (size of the array does not need to be specified).
3.The function prototype must show that the argument is an array.(Eg:int a[])
3.17 What are the rules to pass a two-dimensional array to a
function?
Like 1-D arrays, we can also pass multi-dimensional arrays to functions.
The function must be called by passing only the array name.
In the function declaration and definition, we must indicate that the
array has two dimensions by including two sets of brackets.
The size of the second dimension must be specified.
The prototype declaration must be similar to the function header.
Example: int add(a[][N],int M,int N);
-
7/29/2019 C programming language functions notes
27/35
3.18 Give an example to pass a two-dimensional array to a function.
The following is a program that calculates the average of all the elements of
a two-dimensional array.
/* A program to calculate average of elements of a 2-D array*/
#include
void main()
{
float avg;
int a[2][2] = {10,20,15,25};
int m=2,n=2;
float average(int a[][n],int m,int n); //function declaration
avg=average(a,m,n); //function call
printf("Average of elements of an array=%f \n",avg);
getch();
}
float average(int a[][2],int m,int n) //function definition
{ int i,j,sum=0;
float avg=0.0;
for(i=0;i
-
7/29/2019 C programming language functions notes
28/35
for(j=0;j
-
7/29/2019 C programming language functions notes
29/35
Example: display(item); where, item is the string name
Like arrays, strings are also passed by address.
3.20 What are the storage classes in C? Explain in detail withnecessary examples.
In C, not only variables have data type, they also have a storage class
associated with them. There are four storage classes in C. They are
1. Automatic variables (auto)
2. External variables (extern)
3. Static variables (static)
4. Register variables (register)
1. Automatic variables: Declared inside a function in which they are utilized.
They are created when the function is called and destroyed automatically
when the function is exited, hence the name automatic. Automatic variables
are therefore private (or local) to a function in which they are declared.
Because of this property, automatic variables are also referred to as localor
internalvariables.
A variable declared inside a function without storage class
specification is, by default, an automatic variable.
Eg: int number; is equivalent to auto int number;
Keyword: auto is the keyword used for automatic variables.
One important feature of automatic variables is that their value cannot
be changed accidentally by what happens in some other function in the
program. This ensures that we may declare and use the same variable name
-
7/29/2019 C programming language functions notes
30/35
in different functions in the same program without causing any confusion to
the compiler.
void function1(void);
main()
{ int m=100; //m is local to main()
function1();
printf(%d \n,m);
getch();
}
void function1()
{ int m=10; //m is local to function1()
printf(%d \n,m);
}
Output: 10 //value of m in function1()
100 //value of m in main()
2. External variables: External variables are those that are alive and active
through out the program. They are also known as global variables. Unlike,
local variables, global variables are accessed by any function in the program.
External variables are declared outside a function.
Keyword: extern
For example, int number;
-
7/29/2019 C programming language functions notes
31/35
float average=10.0;
main()
{ }
function1()
{ . }
function2()
{ . }
The variables number and average are global variables since they are
declared outside the main(). They are globally available for use in all three
functions.
In case a local variable and a global variable have a same name, then the
local variable will have precedence over the global one in the function where
it is declared.
The main function cannot access the variable if it has been declared after the
main function. This problem can be solved by declaring the variable with the
storage class extern.
void printline(void);
is equivalent to
extern void printline(void);
3. Static variables: The value of the static variables persists until the end of
the program. A variable can be declared using the keyword static.
Eg: static int x;
-
7/29/2019 C programming language functions notes
32/35
static float y;
A static variable may be either an of internal type or external type depending
on the place of declaration.
Internal static variables are similar to the auto variables except that
they are alive through out the program. Hence, they can be used to
retain values between function calls.
Static variable is initialized only once, when the program is compiled.
It is never initialized again.
An external static variable is declared outside of all functions and is
available to all the functions in that program. The difference between a
static external variable and a simple external variable is that the static
external variable is available only within the file where it is defined
while the simple external variable can be accessed by other files.
Program to illustrate static variable:
void stat();
void main()
{ int i;
for(i=0;i
-
7/29/2019 C programming language functions notes
33/35
printf(x=%d \n,x);
}
Output: x=1
x=2
x=3
4. Register variables: A variable that should be kept in one of the machines
registers, instead of keeping in the memory (where variables are normally
stored) has to be declared using the storage class register.
Eg: register int count;
Advantage: Since register access is much faster than memory access, it
leads to faster execution.
Note:
Most compilers allow only int or char variables to be placed in the
register.
Since, only a few variables can be placed in a register, it is important
to carefully select the variables for this purpose. However, C compiler
automatically converts the register variables into non-register
variables once the limit is reached.
3.21 Write a short note on nested blocks.
A set of statements enclosed in a set of braces is known as a blockor a
compound statement. A block can has its own declarations and other
statements. It is also possible to have a block of such statements inside the
body of a function or another block, thus creating what is known as nested
blocks as shown below.
-
7/29/2019 C programming language functions notes
34/35
main()
{ int a=10;
int b=10;
{ int a=0;
int c=a+b;
printf(Inner block,c=%d\n,c);
.}
c=a+b;
printf(Outer block,c=%d,c);
}
Output: Inner block,c=10
Outer block,c=20
Explanation: The scope of variables inside the inner block is pertained till
the end of the inner block. So here, a is declared and initialized to 0 so, c=
a+b that means c=0+10 =10.
The scope of outer block variables is pertained till the end of
the program. So, after inner block c= a+b. Here, a=10 and b= 10 are there,
so c=10+10=20.
3.22 Define the terms scope, visibility and lifetime.
Scope: The region of a program in which a variable is available for use.
-
7/29/2019 C programming language functions notes
35/35
Visibility: The programs ability to access a variable from the memory.
Lifetime: The lifetime of a variable is the duration of time in which a variable
exists in the memory during execution.
3.33 Compare the scope and lifetime of variables belonging to all
storage classes.
Storage
class
Where declared Visibility (active) Lifetime (alive)
extern Before all
functions (global)
Entire file plus other
files where variable
is declared
Global
static Before all
functions
Only in the file Global
static Inside a function Only in that function Global
None or auto Inside a function Only in that function Until end of the
function
register Inside a function Only in that function Until end of the
function