Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Unit 7 User Defined Function (2)

Unit 7 covers user-defined functions in programming, detailing their advantages, elements, and types. It explains the structure of functions, including declaration, definition, and calling, as well as the differences between library functions and user-defined functions. Additionally, it discusses passing arguments by value and reference, along with examples of various function types and their implementations.

Uploaded by

lanusha820
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit 7 User Defined Function (2)

Unit 7 covers user-defined functions in programming, detailing their advantages, elements, and types. It explains the structure of functions, including declaration, definition, and calling, as well as the differences between library functions and user-defined functions. Additionally, it discusses passing arguments by value and reference, along with examples of various function types and their implementations.

Uploaded by

lanusha820
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Unit 7 User Defined

Function
Bishon Lamichhane
Topics
7.1. Introduction to Function
7.2 Advantages of Function
7.3. Elements of User-defined Function
7.3.1. Function Definition
7.32. Function Prototype
7.3.3. Function Parameters
7.4. Storage Class
7.5. Scope Rules

Compiled by Bishon 2
Topics
7.6. Category of Functions values
7.6.1. Functions with no arguments and no return values
7.6.2. Functions with arguments and no return valuers
7.6.3. Functions with arguments and return values
7.6.4. Functions with no arguments and return values
7.7 Recursive functions
7.8. Function Call by Values and Reference
7.9. passing Array and String to Function

Compiled by Bishon 3
Introduction
➢ A function is a self-contained block code that performs a particular
task. Functions are used to encapsulate a set of operations and return
information to the main program.
➢ Function is necessary in programming because the use of function
provides several benefits:
1. It makes programs significantly easier to understand and maintain.
2. Well written functions may be reused in multiple programs.
3. Different programmers working on one large project can divide the
workload by writing different functions.
4. Programs that use functions are easier to design, program, debug and
maintain.
Compiled by Bishon 4
➢ Programmers prefer using user defined function because it makes
program easier to understand and maintain by modularizing the
program.
➢ A program is divided into small modules so that program becomes
systematic and locating the bugs will be easier. It also reduces the
redundancy of codes.
Merits of user-defined function:
➢ Program can be modularized through the intelligent use of user
defined function.
➢ The use of user defined function avoids the needs for redundant
programming of same instructions.
➢ Program that use functions are easier to design, debug and maintain.
Compiled by Bishon 5
Types of Functions
➢ There are two types of functions. They are:
➢Library functions
➢User-defined functions
Library functions
➢ In C programming, library functions are pre-defined functions
provided by the C Standard Library and other libraries that offer
various functionalities.
➢ These functions are declared in header files, and we can use them
in our C programs by including the appropriate header files and
calling the functions as needed. Here are some common categories
of library functions in C:
Compiled by Bishon 6
i.Input and Output Functions:
➢printf: Used for formatted output.
➢scanf: Used for formatted input.
➢fprintf and fscanf: Used for file I/O (input/output).
➢getchar and putchar: Used for single character input and output.
ii.Mathematical Functions:
➢sqrt: Calculates the square root of a number.
➢pow: Raises a number to a power.
➢sin, cos, tan: Trigonometric functions.
➢fabs: Returns the absolute value of a floating-point number.

Compiled by Bishon 7
iii.String Functions:
➢strlen: Returns the length of a string.
➢strcpy and strncpy: Copy strings.
➢strcat and strncat: Concatenate strings.
➢strcmp: Compare two strings.
iv.Memory Functions:
➢malloc, calloc, realloc: Allocate memory dynamically.
➢free: Deallocate memory.

Compiled by Bishon 8
v.Date and Time Functions:
➢ time: Returns the current time.
➢ ctime: Converts a time value to a string.
➢ strftime: Formats time according to a specified format.
User Defined Function
➢ A user-defined function in C is a block of code that encapsulates a
specific task or set of tasks.
➢ It allows us to break down our program into smaller, manageable
parts, making our code more modular and easier to maintain.

Compiled by Bishon 9
Library Functions User-defined Functions
1.They are predefined functions/ built 1.They are the function which are
in functions in C library. created by the user as per his own
requirements.
2.They are part of header files (such as 2.They are part of the program which is
stdio.h,math.h) which is called at compiled at runtime.
runtime.
3.The name of function ID is given by 3.The name of function ID is declared
developers which can't be changed. by user which can be changed.
4.The function name, its return type, 4.The user has choice to choose its
their argument number & types have name, return type, argument and their
been already defined. types.
5.Example: printf(), scanf(), sqrt(), 5.Example: int fact(int n)
Compiled by Bishon 10
pow(), etc.
Elements of User Defined Function
General Structure of a Program using a User Defined Function
#include<stdio.h>
...........................
Function Declaration/Function Prototype;
void main()
{
Declare Variables;
Input Variables;
Function Call;
//Result Display;??
1
}
Function Definition
2
{
Declare Variables;
Calculation/Processing;
//return Result;??
Compiled by Bishon 11
}
➢ In order to make use of a user-defined function, we need to
understand and use three elements of a user-defined function which are
as follows:
1.Function declaration
2 Function definition
3.Function call
Function Declaration
➢ Function declaration is simply declaring the name of the function, the
arguments and their types and the return type of the function.

Compiled by Bishon 12
➢ User needs to declare a function prior to the definition of the main() function
when the definition of the function is written after the definition of the main()
function.
➢ If the user writes the definition of the function prior to the definition of the
main() function then the need not to declare the function explicitly.
Syntax:
➢ return_type function_name(type1,type2, ......);
➢ where type1,type2,...... are the types of the argument that will be passed to
the function.
Example,
//declaring an user defined function which will be defined later
float addNumbers(float, float);
Compiled by Bishon 13
Function Definition
➢ Function definition includes the parts of the function declaration along
with the body or code-block for the function. User can define a function
before or after the main() function.
Syntax:
return_type function_name(type1 Arg1,type2 Arg2, ......)
{
Function_Body;
}
Here, Arg1, Arg2,.... are the formal arguments, which are variables of
respective types.

Compiled by Bishon 14
Example,
//defining an user defined function which has been declared earlier.
float addNumbers(float a, float b)
{
return (a+b);
}
Function Call
➢ Calling an user defined function is similar to the calling of library
functions, write the name of the function and provide the arguments. If we
need to store the returned data in a variable, then assign this call to a
variable.
Syntax:
Compiled by Bishon 15
return_type_variable= function_name(arg1,arg2,.....);
➢ where arg1,arg2,.... are the actual arguments that are passed to the
function. The values of actual arguments are copied to the formal
arguments respectively.
Example,
int main()
{
float result;
/* calling user defined function from the main function */
result = addNumbers(0.5, 0.8);
printf("Sum=%f",result);
return 0;
}
Compiled by Bishon 16
Types of User-Defined Functions
➢ Depending upon the presence of arguments and the return type, the user-
defined functions can be classified into four categories.
1.Function with no arguments and no return type
2.Function with no arguments but having return type
3.Function with arguments and no return type
4.Function with both arguments and return type
Function with no arguments and no return type
➢ Function with no argument means the called function does not receive
any data from calling function and function with no return type means
calling function does not receive any data from the called function. So,
there is no data transfer between calling and called function.
Compiled by Bishon 17
C program to calculate the area of square using the function with no
arguments and no return values
#include <stdio.h>
void area(); //function prototype
void main()
{
area(); //function call
}
void area()
{
int square_area,square_side;
printf("Enter the side of square :");
scanf("%d",&square_side);
square_area = square_side * square_side;
printf("Area of Square = %d",square_area);
Compiled by Bishon 18
}
Explanation: In the above program, void area( ) function calculates
area and no arguments are passed to this function. The return type of
this function is void and hence return nothing.
Function with no arguments but having return type
➢ As said earlier, function with no arguments means called function
does not receive any data from calling function and function with one
return value means one result will be sent back to the caller from the
function.
C program to calculate the area of square using the function with no
arguments and one return values
#include <stdio.h>
int area(); //function prototype with return type int
Compiled by Bishon 19
void main()
{
int square_area;
square_area = area(); //function call
printf("Area of Square = %d",square_area);
}
int area()
{
int square_area,square_side;
printf("Enter the side of square :");
scanf("%d",&square_side);
square_area = square_side * square_side;
return square_area;
} Compiled by Bishon 20
➢ Explanation: In the function int area( ), no arguments are passed but
it returns an integer value square_area.
Function with arguments and no return type
➢ Here, function will accept data from the calling function as there are
arguments. However, since there is no return type, nothing will be
returned to the calling program. So it’s a one-way type
communication.
C program to calculate the area of square using the function with
arguments and no return values:
#include <stdio.h>
void area( int); //function prototype
int main()
{
Compiled by Bishon 21
int square_side;
printf("Enter the side of square :");
scanf("%d",&square_side);
area(square_side); //function call
return 0;
}
void area(int square_side)
{
int square_area;
square_area = square_side * square_side;
printf("Area of Square = %d",square_area);
}
Explanation: In this function, the integer value entered by the user in
square_side variable is passed to the function area( ). The called
function has void as a return type; as a result, it does not return value. 22
Compiled by Bishon
Function with both arguments and return type
➢ Function with arguments and one return value means both the calling
function and called function will receive data from each other.
➢It’s like a dual communication.
C program to calculate the area of square using the function with
arguments and one return values
#include <stdio.h>
int area(int); //function prototype with return type int
void main()
{
int square_area,square_side;
printf("Enter the side of square :");
scanf("%d",&square_side);
square_area = area(square_side); //function call
printf("Area of Square = %d",square_area);
Compiled by Bishon 23
}
int area(int square_side)
{
int square_area;
square_area = square_side * square_side;
return square_area;
}
Actual Parameter Formal Parameter
1.Parameter used in function call 1.Parameter used in first line of function
in know as actual parameter. definition in known as formal
parameter.
·2.Actual parameter may be simple 2.Formal parameter must be variables.
constants, variables or
expressions.
3.Actual parameter is not preceded 3.Formal parameter is preceded by their
24
by data types. respective data type.
WAP to find the factorial of a number using function.
#include<stdio.h>
int factorial(int n) void main()
{ {
int i,fact=1; int num,f;
for(i=1;i<=n;i++) printf("Enter an integer:\n");
{ scanf("%d",&num);
fact=fact*i; f=factorial(num);
} printf("Factorial of %d is %d",num,f);
return fact; }
}
Output:
Enter an integer:
6
Factorial of 6 is 720
Compiled by Bishon 25
WAP to find the hcf of two numbers using function
#include<stdio.h>
int HCF(int a, int b)
{
int i,smallest,hf;
smallest=(a<b)?a:b;
for(i=smallest;i>=1;i--)
{
if(a%i==0&&b%i==0)
{
hf=i;
break;
}
}
return hf;
Compiled by Bishon 26
}
void main()
{
int num1,num2,hf;
printf("Enter two numbers:\n");
scanf("%d%d",&num1,&num2);
hf=HCF(num1,num2);
printf("HCF of %d and %d is %d",num1,num2,hf);
}

Output:
Enter two numbers:
25
30
HCF of 25 and 30 is 5 Compiled by Bishon 27
Ways of Passing Arguments to a Function
➢ We can pass arguments to a function in two ways:
i. Pass by value –
➢Pass by value means to call the function by passing the value as
argument to the function.
➢In this method, changes made to the formal argument in the called
function has no effect on the values of actual argument in the calling
function.

Compiled by Bishon 28
#include<stdio.h>
void swap(int,int);
void main() void swap(int p, int q)
{ {
int x=2,y=3; int temp;
printf ("The values before swap are: "); temp = p;
printf ("x=%d and y=%d", x,y); p = q;
swap (x,y); // pass by value q=temp;
printf ("\n The values after swap are: "); }
printf ("x=%d and y=%d", x,y);
}
Output:
The values before swap are: x=2 and y=3
The values after swap are: x=2 and y=3
Compiled by Bishon 29
ii. Pass by reference
➢ Pass by reference means to call the function by passing
address(reference) as argument to the function.
➢ In this method, we can change the value of actual argument from the
called function.
Example:
#include<stdio.h>
void swap(int *,int *);
void main()
{
int x=2,y=3;
printf ("The values before swap are: ");
printf ("x=%d and y=%d", x,y);
Compiled by Bishon 30
swap(&x,&y); // Pass by reference
printf ("\nThe values after swap are: ");
printf ("x=%d and y=%d", x,y);
}
void swap(int *p, int *q)
{
int temp;
temp = *p;
*p=*q;
*q=temp;
}
Output:
The values before swap are: x=2 and y=3
The values after swap are: x=3 and y=2
Compiled by Bishon 31
WAP to count number of even digits and odd digits in an integer using pass
by reference
#include<stdio.h>
void countEvenOdd(int num,int *ec, int *oc)
{
int digit;
do
{
digit=num%10;
if(digit%2==0)
*ec=*ec+1;
else
*oc=*oc+1;
num=num/10;
}while(num!=0);
Compiled by Bishon 32
}
void main()
{
int num,even_count=0,odd_count=0;
printf("Enter an integer:\n");
scanf("%d",&num);
countEvenOdd(num,&even_count,&odd_count);
printf("%d consists of %d even digits and %d odd
digits.",num,even_count,odd_count);
}

Output:
Enter an integer:
32451
32451 consists of 2 even digits andCompiled
3 odd digits.
by Bishon 33
Recursive Function
➢ A recursive function is defined as a function that calls itself to solve a
smaller version of its task until a final call is made which does not
require a call to itself. Every recursive solution has two major cases,
they are:
i. Base case, in which the problem is simple enough to be solved
directly without making any further calls to the same function.
ii. Recursive case, in which first the problem at hand is divided into
simpler sub parts. Second the function calls itself but with sub parts of
the problem obtained in the first step. Third, the result is obtained by
combining the solutions of simpler sub-parts.
➢ Therefore, recursion defines large and complex problems in terms of
a smaller and more easily solvable problem.
Compiled by Bishon 34
➢ A recursive function has the following general form:
return_type function_name( Pass appropriate arguments )
{
if it is a simple case
return the simple value // base case or stopping condition
else call function with simpler version of problem
}
➢ For a recursive function to stop calling itself, we require some type of
stopping condition.
➢ If it is not the base case, then we simplify our computation using the
general formula.

Compiled by Bishon 35
➢ To understand recursive functions, let us take an example of
calculating factorial of a number.
➢ To calculate n!, what we have to do is multiply the number with
factorial of the number that is 1 less than that number. In other
words, n!=n*(n-1)!
✓ Let us say we need to find the value of 5!
5!=5*4*3*2*1 =120
✓ This can be written as 5!=5*4!, where 4!=4*3!
✓ Therefore, 5!=5*4*3!
✓ Similarly, we can also write 5!=5*4*3*2!
✓ Expanding further, 5!=5*4*3*2*1!
✓ We know, 1!=1

Compiled by Bishon 36
➢Therefore, the series of problem and solution can be given as
shown below:
PROBLEM SOLUTION
5! 5*4*3*2*1!
= 5*4! = 5*4*3*2*1
= 5*4*3! = 5*4*3*2
= 5*4*3*2! = 5*4*6
= 5*4*3*2*1! = 5*24
= 120

Compiled by Bishon 37
Program to calculate factorial of a given number using recursion
#include<stdio.h>
int factorial(int n) void main()
{
{ int num, fact;
if(n==0) printf("Enter an integer:\n");
return 1; scanf("%d",&num);
else fact=factorial(num);
return n*factorial(n-1); printf("Factorial of %d is %d.",num,fact);
}
}
Output:
Enter an integer:
7
Factorial of 7 is 5040.
Compiled by Bishon 38
WAP to find 𝒙𝒚 using recursive function where x is floating point number
and y is unsigned integer
#include<stdio.h>
float power(float x,unsigned int y)
{
if(y==0)
return 1;
else
return x*power(x,y-1);
}

Compiled by Bishon 39
void main()
{
float x,result;
unsigned int y;
printf("Enter the value of x and y:\n");
scanf("%f%u",&x,&y);
result=power(x,y);
printf("%.2f to the power %u is %.3f",x,y,result);
}
Output:
Enter the value of x and y:
.5
3
0.50 to the power 3 is 0.125
Compiled by Bishon 40
Program to calculate nth term of fibonacci series
#include<stdio.h>
int fibonacci(int n)
{
if(n==1)
return 0;
else if(n==2)
return 1;
else
return fibonacci(n-2)+fibonacci(n-1);
}

Compiled by Bishon 41
void main()
{
int n,nthTerm;
printf("Enter the value of n:\n");
scanf("%d",&n);
nthTerm=fibonacci(n);
printf("Nth term is %d",nthTerm);
}
Output:
Enter the value of n:
5
Nth term is 3Compiled by Bishon 42
Finding the sum up to nth term using recursive function
➢In order to find the sum upto nth term we use the following approach:
return type function_name(…, int num_terms)
{
if(num_terms==1)
return first_term;
else
return nth_term+ function_name(…,num_terms-1);
}
Where … are the other parameters.

Compiled by Bishon 43
➢Example 1+2+3+4+5+…+n
Here general term i.e t(n)=n. So we replace nth term with n and first term is 1
#include<stdio.h>
int sum_upto_n(int);
void main()
{
int num_terms,sum;
printf("Enter number of terms:\n");
scanf("%d",&num_terms);
sum=sum_upto_n(num_terms);
printf("The sum upto nth term is: %d",sum);
}
Compiled by Bishon 44
int sum_upto_n(int num_terms)
{
if(num_terms==1)
return 1;
else
return num_terms+sum_upto_n(num_terms-1);
}

Output
Enter number of terms:
10
The sum upto nth term is: 55

Compiled by Bishon 45
12-22+32-42 ........
Here t(n)=(-1)n+1n2 and first term is 1
#include<stdio.h>
int sum_upto_n(int);
int powr(int,int);
void main()
{
int num_terms,sum;
printf("Enter number of terms:\n");
scanf("%d",&num_terms);
sum=sum_upto_n(num_terms);
printf("The sum upto nth term is: %d",sum);
}

Compiled by Bishon 46
int sum_upto_n(int num_terms)
{
if(num_terms==1)
return 1;
else
return
powr(1,num_terms+1)*powr(num_terms,2)+sum_upto_n(num_terms-1);
}
int powr(int x, int n)
{ Output:
if(n==0) Enter number of terms:
return 1; 4
else The sum upto nth term is: -10
return x*powr(x,n-1);
} Compiled by Bishon 47
Sin(x)=x-x3/3!+x5/5!-x7/7!+x9/9! .........
Here t(n)=(-1 )n-1 x(2n-1) /(2n-1)! where n=1,2,3,4,… and first term is x
#include<stdio.h>
float sum_upto_n(float,int);
float nth_term(float,int);
float powr(float,int);
int factorial(int);
void main()
{
int num_terms;
float x, sum;
printf("Enter the value of x and number of terms:\n");
scanf("%f%d",&x,&num_terms);
sum=sum_upto_n(x, num_terms);
printf("The sum upto nth term is: %f",sum);
48
} Compiled by Bishon
float sum_upto_n(float x, int num_terms)
{
if(num_terms==1)
return x;
else
return nth_term(x,num_terms)+ sum_upto_n(x, num_terms-1);
}
float nth_term(float x, int n)
{
float numerator;
int denominator;
numerator=powr(-1,n-1)*powr(x,2*n-1);
denominator=factorial(2*n -1);
return numerator/denominator;
} Compiled by Bishon 49
float powr(float x, int n)
{
if(n==0)
return 1;
else Output:
return x * powr(x,n-1); Enter the value of x and number of terms:
} 25
int factorial(int n) The sum upto nth term is: 0.909347
{
if(n==0 || n==1)
return 1;
else
return n*factorial(n-1);
}
Compiled by Bishon 50
Passing Arrays to User-Defined Functions
➢ There are 3 rules that govern the passing of arrays to user defined
functions:
➢The function must be called by passing only the name of the array
and its size.
➢In the function definition, the formal parameters must be an array
type; the size of the array does not need to be specified.
➢The function prototype must show that the argument is an array.

Compiled by Bishon 51
Passing 1D Array to Function
➢ We can pass whole array element from function by passing the name
of the array.
➢ The array name refers to the first byte of the array in memory.
➢ The address of rest of the elements in the array can be calculated
using the array name and the index value of the element. Therefore,
when we need to pass an entire array to a function, we can simply
pass the name of the aray as shown below:
void func(int [ ],int);

Compiled by Bishon 52
void main( )
{
int arr[5]={1,2,3,4,5};
func(arr,5);
}
void func( int arr[],int n)
{
int i;
for(i=0;i<n;i++)
printf(“%d”,arr[i]);
}
➢ Here an array named 'arr' is passed to a function 'func' to display its
elements.

Compiled by Bishon 53
Passing 2D Array to Function
➢ To pass a two dimensional array to a function we have to pass the
array name and size (row and column) as the actual argument.
➢ The array name stores the starting address of the memory area
reserved for the array.
➢ The size of dimension except the first, must be included in the
function prototype (declaration) and in function definition.

Compiled by Bishon 54
# include < stdio. h>
void display (int [ ] [10], int, int); // function declaration
void main ( )
{
int a [10] [10], i, j;
for (i = 0; i < 10; i + +)
{
for (j = 0; j < 10; j + + )
{
scanf("% d", & a[i] [j]);
}
}
display (a, 10, 10), // Function call
}
Compiled by Bishon 55
void display (int b[ ] [10], int m, int n) // Function definition
{ int i,j;
printf ("the entered array is:");
for (i = 0; i < m; i + +)
{
for (j = 0; j < n; j + +)
{
printf ("% d \ t", b[i] [j]);
}
printf ("\n");
}
}
➢ Here, a 2D array is passed to a function display ( ) to print its
elements. Compiled by Bishon 56
Passing string to a function

Function declaration to accept one dimensional string


➢We know that strings are saved in arrays so, to pass an one
dimensional string to a function we will have the following
declaration.
returnType functionName(char []);
➢Example:
void displayString(char []);
➢In the above example we have a function by the name displayString
and it takes an argument of type char and the argument is an one
dimensional array as we are using the [] square brackets.

Compiled by Bishon 57
Passing one dimensional string to a function
➢To pass a one dimensional string to a function as an argument we just
write the name of the string array variable.
➢In the following example we have a string array variable message and it
is passed to the displayString function.
#include <stdio.h>
void displayString(char []);
void main()
{
char message[] = "Hello World";
displayString(message); Output:
} String: Hello World
void displayString(char str[])
{
printf("String: %s\n", str);
Compiled by Bishon 58
}
WAP to read a string in the main(), pass it to a function that reverse the string.
Display the reverse string from main().
#include<stdio.h>
void udStrrev(char str[]) void main()
{ {
int i,j,len; char str[100];
char temp; printf("Enter a string:\n");
for(len=0;str[len]!='\0';len++); gets(str);
for(i=0,j=len-1;i<j;i++,j--) udStrrev(str);
{ printf("Reverse string is %s",str);
temp=str[i]; }
str[i]=str[j]; Output
str[j]=temp; Enter a string:
} Nepal
} Compiled by Bishon Reverse string is lapeN 59
Classification of Variables According to the Scope and Extent
(Storage Class)
➢ Classification of the variables according to the scope and extent
(storage class) are as follows:
1.Automatic
2.External
3.Static
4.Register
➢ The term scope (of a variable) means that portion of the program
where the variable is 'known' (accessible).

Compiled by Bishon 60
Automatic:
➢Unless specified otherwise, a variable declared in a function is of type
auto (an automatic variable). For example,
int linecount;
➢ The word auto may be used to declare a variable as automatic as in
auto int linecount; but it is almost never used.
➢ Storage is allocated to the variables each time the function is called
and is released when the function returns. There is no connection
between the value left by a previous call and the initial value of the
next call. When a value is not given explicitly to the variable, we can
assume that it contains garbage.
➢ The scope of an automatic variable is the function in which it is
declared. Another function may use a variable of the same name
Compiled by Bishon 61
without conflict.
External
➢A variable declared outside of any function is considered to be
external. There can be only one definition of an external variable in a
C program.
➢ Consider the following program structure and assume that the entire
program is in one file.
int digit;
main ()
{
..........
..........
}
int count; Compiled by Bishon 62
fun1 ()
{
extern int number;
}
fun2 ()
{
extern int digit;
}
int number;
➢ The scope of digit is the entire program if the word ‘extern is omitted
from the declaration, so it becomes simply
int digit
Compiled by Bishon 63
➢ The function with this declaration reference digit as local variable
➢ To summarize,
A variable is global if it is defined outside of any function.
The extern declaration is mandatory if a function wishes to use a
global variable but appears before the definition of the variable.
If a variable, declared as global is redeclared in a function, then the
local definition is used within that function. In this case, the function
has no access to the global variable.
The global variable can be used in any function which comes after
the definition as is in the same file. However it is good programming
practice to include an external declaration in those functions which
use the variable.
Compiled by Bishon 64
Static:
➢ A variable is declared to be static by prefixing its normal declaration with
the word static as in
static int a;
➢ In the absence of explicit initialization, C guarantees that static variable will
be initialized to 0.
➢ A static variable can be either internal or external.

Compiled by Bishon 65
Internal static:
If the declaration appears inside a function as in:
fun ()
{
static int a = 0;
}
➢Then the variable is known only inside the function. Storage is
allocated to an internal static variable once. This storage (and the
value it contains) is retained between calls to the function.

Compiled by Bishon 66
External static
➢If the declaration appears outside of any function as in:
static int a = 0;
fun ()
{
..........
}
➢Then the variable is known in the remainder of the file containing
the declaration. In above example, a can be incremented by any
function following the declaration, provided it is in the same file.

Compiled by Bishon 67
Register:
➢This storage class is usually applied to a variable which will be
heavily used in the program. Register may be applied only to
automatic variables and to the formal parameters of functions.
➢ Example of register declarations are:
void fun (register int n, register char ch)
{
register void *p;
}
➢Where possible, a register variable is assigned to a machine register
rather than a normal memory location. Presumably this will result in a
smaller, faster object program since a register access is much faster
Compiled by Bishon 68
than a memory access.
Unit 7 Ends Here

Compiled by Bishon 69

You might also like