SlideShare a Scribd company logo
1 of 75
VELAMMAL ENGINEERING COLLEGE
An Autonomous Institution, Affiliated to Anna University Chennai, &
Approved by AICTE Delhi
UNIT III
FUNCTIONS AND
STORAGE CLASSES
1
Velammal Engineering college/Dept. of CSE
UNIT-III FUNCTIONS AND STORAGE CLASSES
Defining a function – Accessing a function –
Function prototypes – Passing arguments to a
function – Passing arrays to functions – Function
with string - Recursion – Storage classes
Velammal Engineering college/Dept. of CSE 2
Introduction
▪ A function is a self-contained block of program statements
that performs a particular task.
Need for functions:
▪ It breaks up a program into easily manageable chunks and
makes programs easier to understand.
▪ Improves the reusability of code.
▪ Easy debugging of code.
▪ Different programmers working on one large project can divide
the workload by writing different functions.
Using functions:
▪ All C programs contain atleast one function, called main()
when execution starts.
▪ When a function is called, the code contained in that function
is executed.
▪ When the function has finished executing, control returns to
the point at which that function was called.
Questions:
• What is mean by function?
• Advantages of functions?
Velammal Engineering college/Dept. of CSE 6
Using functions:
Function Prototype Declaration:
return_datatype function_name(datatype var1, datatype var2, …);
▪ return_datatype : specifies the type of data given back by the function
after executing a specific task.
▪ function_name: this is the name given to the function. It allows the
same rules as that for any valid variable in C.
▪ datatype var1,...... : specifies the datatype of the variables passed to
the function.
Rules:
▪The name of the function is global.
▪No function can be defined in another function
body.
▪Number if arguments must agree with the
number of parameters specified in the prototype.
▪The function return type cannot be an array or a
function type.
Function Definition:
▪ The collection of program statements in C that describes the specific task
done by the function is called function definition.
▪ It consists of
▪ Function header
▪ Function body
return_datatype function_name(datatype var1, datatype var2, …) /*
Function header */
{
/* Function Body */
}
▪ No semicolon in function header.
▪ The list of variables in the function header is also referred to as the
formal parameters.
Function Call:
▪ Syntax:
function_name(variable1, variable2,...);
Or
var_name = function_name(variable1, variable2,...);
▪ If there are no arguments to be passed in the function,
function_name( );
Or
var_name = function_name( );
▪ Information will be passed to the function via special identifiers called
arguments or actual parameters and returned via the return statement.
Rules for parameters:
• The number of parameters in the actual and formal parameter
lists must be consistent.
• Parameter association in C is positional.
• Actual parameters and formal parameters must be of
compatible data types.
• Actual (input) parameters may be a variable, constant, or any
expression matching the type of the corresponding formal
parameter.
Question:
• What are the components of function?
Velammal Engineering college/Dept. of CSE 13
Program 1: Sum of two numbers
#include<stdio.h>
int sum(int, int);/*Function declaration*/
void main()
{
int i,j,k;
printf(“Enter the values for i and j”);
scanf(“%d %d”,&i, &j);
k = sum(i,j); /* Function Call */
printf(“Sum of two values = %d”,k);
}
int sum(int a, int b) /* Function
Definition */
{
return(a+b);
}
Output:
Enter the values for i and j 10
20
Sum of two values = 30
Passing arguments to a function:
▪ The technique used to pass data to a function is known as
parameter passing.
▪ Data are passed to a function using two techniques:
1. Call by value or Pass by value.
2. Call by reference or Pass by reference.
n1,n2 – actual parameters
a, b – formal parameters
• In programming, argument refers to the variable passed to the function. In the
above example, two variables n1 and n2 are passed during the function call.
• The parameters a and b accepts the passed arguments in the function definition.
These arguments are called formal parameters of the function.
Velammal Engineering college/Dept. of CSE 16
Call by Value mechanism:
▪ Here, a copy of the data is made and the copy is sent to the
function.
▪ Since, only copies are passed, the values in the argument
remains unchanged.
▪ As only copies of the values held in the arguments are sent
to the formal parameters, the function cannot directly
modify the arguments passed.
An Example of Call by value Mechanism:
#include <stdio.h>
void swap(int, int);
int main()
{
int x, y;
printf("Enter the value of x and yn");
scanf("%d%d",&x,&y);
printf("Before Swapping nx = %dty = %dn", x, y);
swap(x, y);
printf("After Swappingnx = %dty = %dn", x, y);
return 0;
}
void swap(int a, int b)
{
int temp;
temp = b;
b = a;
a = temp;
printf(“Inside Swap function: Values of a and b is %d
%dn",a,b);
}
Output:
Enter the value of x and y
50 30
Before Swapping
x = 50 y = 30
Inside Swap function: Values of a
and b is 30 50
After Swapping
x = 50 y = 30
Call by reference mechanism:
▪ Here, the address of the data is sent rather than a copy.
▪ In this case, the called function can change the original data
in the calling function.
▪ Details will be discussed in the chapter on pointers.
Call by reference
Velammal Engineering college/Dept. of CSE 20
Difference between call by value and call by
reference in c
No. Call by value Call by reference
1
A copy of the value is passed into the
function
An address of value is passed into the
function
2
Changes made inside the function is limited
to the function only. The values of the
actual parameters do not change by
changing the formal parameters.
Changes made inside the function validate
outside of the function also. The values of the
actual parameters do change by changing the
formal parameters.
3
Actual and formal arguments are created at
the different memory location
Actual and formal arguments are created at
the same memory location
Velammal Engineering college/Dept. of CSE 21
Function Usage in various ways:
▪ Functions can be used in a program in various ways:
a. Function that perform operations on their parameters
and return a value.
b. Function that manipulates information on their
parameters and return a value that simply indicates the
success or failure of that manipulation.
c. Function having no return type that is strictly
procedural.
Function that perform operations on their
parameters and return a value:
#include <stdio.h>
int GCD(int, int);
int main()
{
int n1, n2, n;
printf("Enter two numbers: ");
scanf("%d %d",&n1,&n2);
n = GCD(n1, n2);
printf(“n GCD of %d and %d is %d”,n1, n2,n);
return 0;
}
int GCD(int x, int y)
{
int result = 1, k = 2;
while(k <= x && k <= y)
{
if(x % k == 0 && y % k == 0)
result = k;
k++;
}
return result;
}
• Example: GCD of the numbers 10 and 12.
10 has for divisors' list: 1,2,5,10
12 has for divisors' list: 1,2,3,4,6,12
The greatest common divisor (of these lists) is 2 (The largest number
in all lists).
So, GCD(10,12) = 2
Velammal Engineering college/Dept. of CSE 24
Function that manipulates information on their parameters and return a
value that simply indicates the success or failure of that manipulation.
#include <stdio.h>
bool isPrime(int);
int main()
{
int n, d = 2;
printf("Enter the number: ");
scanf("%d",&n);
printf(“n Prime factors of %d are n”,n);
for (d = 2; d <= n/2; d++)
if(n %d == 0 && isPrime(d))
printf(“%dt”,d);
return 0;
}
bool isPrime(int x)
{
int k;
for( k = 2; k <= x/2; k++)
if(x % k == 0)
return 0;
return 1;
}
Output:
Enter the number: 51
Prime factors of 51 are
3 17
Function having no return type that is strictly procedural.
❑When we pass the value of a variable to a function, a copy of that value
gets assigned to the parameter.
❑Changing the value of the parameter within the called function does not
affect the value of the variable in the calling function.
❑But, things are different when an array is passed to a function. What we
are actually passing is the memory address of the array.
❑If the called function changes specific entries in the array, these entries
remain changed when control gets back to the calling function.
❑So, when arrays or strings are passed to a function, call by value
mechanism is not followed.
Function having no return type that is strictly procedural.
#include <stdio.h>
void sort(int [ ], int);
int main()
{
int i;
int arr[10] = { 3,2,7,0,6,4,9,8,1,5};
printf(“n The array before sorting:n");
for (i = 0; i < 10; i++)
printf(“%dt”,arr[i]);
sort(arr,10);
printf(“n The array after sorting:n");
for (i = 0; i < 10; i++)
printf(“%dt”,arr[i]);
return 0;
}
void sort(int a[ ], int n)
{
int i,j,temp;
for(i = 0; i < n-1; i++)
for(j = 0; j < n-i-1; j++)
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
Output:
The array before sorting:
3 2 7 0 6 4 9 8 1 5
The array after sorting:
0 1 2 3 4 5 6 7 8 9
Difference between call by value and call by
reference in c
Velammal Engineering college/Dept. of CSE 28
Passing Arrays to Functions
❑Arrays can also be the arguments of functions. When an array is
passed to a function, the address of the array is passed and not the
copy of the complete array.
❑Therefore, when a function is called with the name of the array as
the argument, address of the first element in the array is handled
over to the function.
❑Since the address of the array is passed, the function has the ability
to modify the contents of the array.
❑Therefore, array is not passed to the function by value.
Passing arrays as arguments: - Average age of students
#include <stdio.h>
float avg_age(int [ ], int);
int main()
{
int i, a[50],n;
float average;
printf(“n How many students?");
scanf(“%d”,&n);
printf(“Enter the age of students:n”);
for (i = 0; i < n i++)
scanf(“%d”,&a[i]);
average = avg_age(a,n);
printf(“n The average age of students: %fn“, average);
return 0;
}
float avg_age(int b[ ], int n)
{
int j;
float sum = 0.0;
for(j = 0; j < n; j++)
sum = sum + b[j];
return sum/n;
}
Passing String to Functions
❑Strings are passed to the functions in the same way as are one-
dimensional arrays.
/* Function to copy one string into another */
#include <stdio.h>
void string_copy(char [ ], char [ ]);
int main()
{
char a[100]; /* Source String */
char b[100]; /* Destination String */
printf(“n Input Source String");
scanf(“%[^n]”, a);
string_copy(b,a);
printf(“n Destination String: %sn“,b);
return 0;
}
void string_copy(char d[ ], char s[ ])
{
int i = 0;
printf(“n Source String: %sn“,s);
for( i = 0; s[i] != ‘0’; i++)
d[i] = s[i];
}
Passing Multidimensional Arrays to Functions
❑Multidimensional arrays are also allowed to be passed as
arguments to functions.
❑Ex. : Matrix
❑Here, first dimension can be omitted in formal parameter.
❑Ex.: int yield(int a[ ][4], int index);
Lifetime:
❑Lifetime is the period during execution of a
program in which a variable or a function exists.
Local Variables
❑Variables declared within the function body are called local
variables.
❑They have local lifetime.
❑Local variables are automatically created at the point of their
declaration within the function body and are usable inside the
function body.
❑They only exist inside the specific function that creates them. They
are unknown to other functions and to the main program.
❑The existence of the local variables ends when the function
completes its task & returns to the calling point.
❑They are recreated each time a function is executed or called.
Global Variables
❑Variables declared outside of all the functions of a program and
accessible by any of these functions are called global variables.
❑The existence and region of usage of these variables are not
confined to any specific function body.
❑Global variables are created at the beginning of program execution
and remain in existence all through the period of the execution of
the program.
❑They are known to all functions in the program and can be used
by these functions as many times as may be required.
❑They do not get recreated if the function is recalled.
SCOPE
▪The region of the program over which the declaration of an
identifier is accessible is called the scope of the identifier.
▪The scope relates to the accessibility, the period of existence, and
the boundary of usage of variables declared in a program.
▪Scopes can be of four types.
▪Block
▪File
▪Function
▪Function prototype
Block scope
• This means that the identifier can only be used in the block in which it
is declared.
• These variables are created at the point of their declaration inside the
block and cease to exist outside it.
• Outside the block, these variables are unknown and non-existent.
• Example:
Velammal Engineering college/Dept. of CSE 37
Function scope
• This applies only to labels. Normally labels are used with goto
statement.
• It simply means that labels can be used anywhere within the function
in which they are defined.
• This includes use before definition.
Velammal Engineering college/Dept. of CSE 38
File scope
• This means that the identifier can be used anywhere in the current
file after the declaration of the identifier.
• This applies to functions and all variables declared outside functions.
• File scope variable is also known as global variable.
Velammal Engineering college/Dept. of CSE 39
Function prototype scope
• In order to improve readability and understandabilty, function
prototypes are usually written with ‘dummy’ variable names.
• For example
double max(double x, double y);
• The identifiers ‘x’ and ‘y’ have function prototype scope, which
terminates at the end of the prototype.
Velammal Engineering college/Dept. of CSE 40
Recursion
❑A recursive function is one that calls itself directly or indirectly to
solve a smaller version of its task until a final call which does not
require a self-call.
❑A function that calls itself is known as a recursive function. And, this
technique is known as recursion.
Recursion
• To prevent infinite recursion, if...else statement (or similar approach)
can be used where one branch makes the recursive call, and other
doesn't.
• Example: Sum of Natural Numbers Using Recursion
Velammal Engineering college/Dept. of CSE 42
Example: Sum of Natural Numbers Using
Recursion
Velammal Engineering college/Dept. of CSE 43
Recursion
❑The following are necessary for implementing recursion:
✔Decomposition into smaller problems of same type.
✔Recursive calls must diminish problem size.
✔Necessity of base case.
✔Base case must be reached.
✔It acts as a terminating condition.
✔It is the building block to the complete solution.
Base Case
❑An instance of a problem the solution of which requires
no further recursive calls is known as the base case.
❑Every recursive algorithm requires atleast one base case in
order to be valid.
Recursive function to find factorial of a number
#include <stdio.h>
int factorial(int);
int main()
{
int n, res;
printf(“Enter the number”);
scanf(“%d”,&n);
res = factorial(n);
printf(“The factorial of %d is %d”,n,res);
return 0;
}
int factorial(int num)
{
if(num == 0)
return 1;
else
return(num * factorial(num - 1));
}
O/P:
Enter the number 4
The factorial of 4 is 24.
Types of Function
• There are two types of functions namely
• Library Functions: Function defined are included with C compilers are
known as library functions. These functions are built-in, pre-compiled
and ready to use.
Example: printf(),sqrt()
• User Defined Functions: Functions defined by an end programmer is
known as user defined function. A programmer can define any
number of function depending on the need.
Example: add()
Velammal Engineering college/Dept. of CSE 47
Function usage based on parameters and
return type
• Based on the prototype, there can be 4 different types of user-
defined functions, they are:
• Function with no arguments and no return value.
• Function with no arguments and a return value.
• Function with arguments and no return value.
• Function with arguments and a return value.
Velammal Engineering college/Dept. of CSE 48
Lifetime:
❑Lifetime is the period during execution of a
program in which a variable or a function exists.
Local Variables
❑Variables declared within the function body are called local
variables.
❑They have local lifetime.
❑Local variables are automatically created at the point of their
declaration within the function body and are usable inside the
function body.
❑They only exist inside the specific function that creates them. They
are unknown to other functions and to the main program.
❑The existence of the local variables ends when the function
completes its task & returns to the calling point.
❑They are recreated each time a function is executed or called.
Global Variables
❑Variables declared outside of all the functions of a program and
accessible by any of these functions are called global variables.
❑The existence and region of usage of these variables are not
confined to any specific function body.
❑Global variables are created at the beginning of program execution
and remain in existence all through the period of the execution of
the program.
❑They are known to all functions in the program and can be used
by these functions as many times as may be required.
❑They do not get recreated if the function is recalled.
Storage Class Specifiers for Variables
• Variables are declared by the type of data they can hold
• The name of a variable is associated with a memory location within the computer
where the value assigned to the variable is stored in the form of bits.
• C provides four storage class specifiers to indicate where the variables
• would be stored
• how long they would exist
• what would be their region of existence
• what would be the default values
• Four storage class specifiers are
• Automatic
• External
• Register
• Static
• Storage class specifier precedes the declaration statement for a variable.
• The general form of the variable declaration statement with storage class specifier
is given as follows:
• storage_class_specifier data_type variable_name;
Velammal Engineering college/Dept. of CSE 52
The storage class – auto
• By default, all variables declared within the body of any function are
automatic.
• To explicitly specify variable as automatic storage class keyword “auto” is
used in the declaration
• For example, the following declaration statement within a function body
• auto char any_alpha; Ex: auto int a=10;
• Variable stored : primary memory of the computer
• Scope : limited within the function body
• Existence : Vanishes when the function completes its specific task and
returns to the invoked main program
• Note – 1. If function body does not include the keyword auto, such declared
variables are implicitly specified as belonging to the automatic storage class
2. Local variables declared within nested blocks in a function
belong by default to the automatic storage class
Velammal Engineering college/Dept. of CSE 53
Example 2 : C program that demonstrates the use of the
automatic storage class variable
#include <stdio.h>
int main(void)
{
auto int a =5;
printf(“n a = %d”,a);
{
int a = 10;
printf(“n a = %d”,a);
printf(“n i = %d”,i);
}
printf(“n a = %d”,a);
return 0;
}
Output
a = 5
a = 10
i = 4199232
a = 5
Velammal Engineering college/Dept. of CSE 54
The storage class – register
• Values stored in registers of the CPU are accessed in much
lesser time than those stored in the primary memory.
• To allow the fastest access time for variables, the register
storage class specifier is used.
• The keyword for this storage class is “register”
• For example, the following declaration statement within a
function body
• register char any_alpha; Ex: register int a=10;
• In most C compilers, the register specifier can only be applied to
int and char type variables; however, ANSI C has broadened its
scope.
Velammal Engineering college/Dept. of CSE 55
The storage class – register
• Variable stored : registers of the CPU
• Scope : Restricted within the region of a function or a block
where it has been declared
• Existence : exists as long as the function or block remains active.
• Default value : unknown, which is interpreted as garbage.
• Note – 1. Storage class of a global variable cannot be specified as
register.
2. Arrays cannot be stored in a registers but they may
still receive preferential treatment by the compiler
depending on C compiler and the operating system
under which it is running
Velammal Engineering college/Dept. of CSE 56
The storage class – register
Note – 3. Global variables with register storage class are not allowed.
4. In C, it is not possible to obtain the address of a register
variable by using ‘&’ operator.
5. In addition, the only storage class specifier that can be
used in a parameter declaration is register.
Velammal Engineering college/Dept. of CSE 57
Example 1 : C program that demonstrates register variables
#include <stdio.h>
int main()
{
int m1 = 5;
register int m2 = 10;
printf("The value of m1 : %d ",m1);
printf("nThe value of m2 : %d ",m2);
return 0;
}
Output
The value of m1 : 5
The value of m2 : 10
Velammal Engineering college/Dept. of CSE 58
Example 2 : C program that demonstrates register variables
#include <stdio.h> /* function declaration */
main() {
register int weight;
int *ptr=&weight ;/*it produces an error when
the compilation occurs ,we cannot get a memory
location when dealing with CPU register*/
}
Output
error: address of register
variable 'weight' requested
Velammal Engineering college/Dept. of CSE 59
The storage class – static
• Two kinds of variables are allowed to be specified as static
variables:
• local variables (internal static variables)
• global variables (external static variables)
• To specify a local variable as static, the keyword “static”
precedes its declaration statement
• For example, the following declaration statement within a
function body
• static int beta;
Velammal Engineering college/Dept. of CSE 60
The storage class – static
Static local variable
• Variable stored : permanent storage
location in the primary memory
• Scope : is usable within functions or blocks
where it is declared and preserves its
previous value held by it between function
calls or between block re-entries
• Existence : once a function is invoked, the
static local variable retains the value in it
and exists as long as the main program is in
execution
• Default value : zero
Static global variable
• Variable stored : stored in the primary
memory
• Scope : accessible by all functions in the
program file where these variables exist and
are declared.
• not available to functions defined earlier in
the same file or not accessible to functions
defined in other files although these may
use the extern keyword
• Existence : exist throughout the period of
the main program
execution
• Default value : zero
Velammal Engineering college/Dept. of CSE 61
Example1 : C program that demonstrates the use of the static
variables and functions
#include <stdio.h>
int main()
{
void show(void);
printf(“n First Call of show()”);
show();
printf(“n Second Call of show()”);
show();
printf(“n Third Call of show()”);
show();
return 0;
}
void show(void)
{
static int i;
printf(“n i=%d”,i);
i++;
}
Output
First Call of show()
i=0
Second Call of show()
i=1
Third Call of show()
i=2
Velammal Engineering college/Dept. of CSE 62
Example 2 : C program that demonstrates the use of the static
variables and functions
#include <stdio.h>
void func(void);
static int count = 5; /* global variable */
int main() {
while(count--) {
func();
}
return 0;
}
/* function definition */
void func( void ) {
static int i = 5; /*local static variable */
i++;
printf("i is %d and count is %dn", i,
count);
}
Output
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
Velammal Engineering college/Dept. of CSE 63
The storage class – extern
• When C program is large, it can be broken up into smaller programs.
• After compiling, each program file can be joined together to form the large program.
• These small program modules that combine together may need some variables that are
used by all of them.
• External storage class variable are accessible to all the small program modules
• These variables are global to all the small program modules that are formed
as separate files.
• The keyword “extern” for declaring such global variables
• For example, the following declaration statement within a function body
• extern int zeta;
• Such global variables are declared like any other variable in one of the program modules
while the declaration of these variables is preceded with the keyword extern in all other
combining program modules (may be a function or a block).
Velammal Engineering college/Dept. of CSE 64
The storage class – extern
• Variable stored : primary memory
• Scope : Accessible by small program modules that form the
large program
• Existence : exists as long as the program is in execution and
their existence does not terminate upon the exit of a function or
a block or a program module from its state of execution
• Default value : zero
Velammal Engineering college/Dept. of CSE 65
/* Program file: pgm1.c */
#include <stdio.h>
#include “pgm2.c” /*link pgm2.c
*/
int i; /*external/global decl*/
void show(void);/*fn prototype*/
int main()
{
i=10;
show();/*call to fn in pgm2.c*/
printf(“n Value of i in pgm1.c=%d
”,i);
return 0;
/* Program file : pgm2.c */
extern int i;
/*fn definition of show()*/
void show() /*fn header */
{
printf(“n Value of i in
pgm2.c=%d”,i);
}
Velammal Engineering college/Dept. of CSE 66
Output
Value of i in pgm2.c=10
Value of i in pgm1.c=10
/* Program file: pgm1.c */
#include <stdio.h>
#include “pgm2.c” /*link
pgm2.c */
int i; /*external/global
decl*/
void show(void); /*fn
prototype */
int main()
{
show(); /*call to fn in
pgm2.c */
printf(“n Value of i in
pgm1.c=%d”,i);
return 0;
}
/* Program file : pgm2.c */
extern int i;
/*fn definition of show()*/
void show() /*fn header ***/
i = 20;
printf(“n Value of i in
pgm2.c=%d”,i);
}
Velammal Engineering college/Dept. of CSE 67
Output
Value of i in pgm2.c=20
Value of i in pgm1.c=20
Velammal Engineering college/Dept. of CSE 68
Storage Class Specifiers for Functions
• The only storage class specifiers that may be assigned with
functions are
✔ extern
✔ static
• The extern signifies that the function can be referenced from other
files- that is,the function name is exported to the linker.
• The static signifies that the function cannot be referenced from other
files- that is the function name is not exported to the linker.
• If no storage class appears in a function definition, extern is
presumed
Velammal Engineering college/Dept. of CSE 69
Linkage
• An identifier’s linkage determines which of the references
to that identifier refer to the same object.
• An identifier’s linkage is determined by whether it appears inside or
outside a function, whether it appears in a declaration of a function (as
opposed to an object), its storage-class specifier, and the linkage of any
previous declarations of the same identifier that have file scope
Velammal Engineering college/Dept. of CSE 70
Linkage
• C defines three types of linkages – external, internal and no linkage
• In general,
• Functions and global variables have external linkage(available to all files
in a program.
• Identifiers with file scope declared as static have internal linkage(known
only within the file in which they are declared)
• Local identifiers have no linkage and are therefore known only within
their own block.
• Two declarations of the same identifier in a single file that have the
same linkage, either internal or external, refer to the same object.
• The same identifier cannot appear in a file with both internal and
external linkage.
Velammal Engineering college/Dept. of CSE 71
/* Program file: animals.c
*/
#include <stdio.h>
static int animals = 8;
const int i = 5;
int call_me(void)
{ printf("%d %d", i,
animals);
}
/* Program file : feed.c
located in a different
translation unit*/
#include <stdio.h> int
main()
{ call_me();
animals = 2;
printf("%d", animals);
return 0;
}
Velammal Engineering college/Dept. of CSE 72
Output
5 8 2
Example : C code to illustrate Internal Linkage
/* Program file: animals.c */
#include <stdio.h>
void foo()
{ int a;
extern int b; // line 1 }
void bar()
{
int c;
c = b; // error
}
int main()
{
foo();
bar();
}
Velammal Engineering college/Dept. of CSE 73
Output
Error: 'b' was not declared
in this scope
Example : C code to illustrate External Linkage
/* Program file: animals.c */
#include <stdio.h>
int x = 10;
int z = 5;
int main()
{
extern int y; // line 2
extern int z;
printf("%d %d %d", x, y, z);
}
int y = 2;
Velammal Engineering college/Dept. of CSE 74
Output
10 2 5
Example : C code to illustrate External Linkage
Thank you
Velammal Engineering college/Dept. of CSE 75

More Related Content

What's hot (20)

Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
 
M11 operator overloading and type conversion
M11 operator overloading and type conversionM11 operator overloading and type conversion
M11 operator overloading and type conversion
 
user defined function
user defined functionuser defined function
user defined function
 
C function presentation
C function presentationC function presentation
C function presentation
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
User Defined Functions in C
User Defined Functions in CUser Defined Functions in C
User Defined Functions in C
 
Pre defined Functions in C
Pre defined Functions in CPre defined Functions in C
Pre defined Functions in C
 
Functions in C
Functions in CFunctions in C
Functions in C
 
C# programs
C# programsC# programs
C# programs
 
Cpp functions
Cpp functionsCpp functions
Cpp functions
 
Functions
FunctionsFunctions
Functions
 
Functions
FunctionsFunctions
Functions
 
Recursion in c
Recursion in cRecursion in c
Recursion in c
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Function in C
Function in CFunction in C
Function in C
 
Functions part1
Functions part1Functions part1
Functions part1
 
Procedure n functions
Procedure n functionsProcedure n functions
Procedure n functions
 

Similar to 3 Function & Storage Class.pptx

358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2sumitbardhan
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxsangeeta borde
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfTeshaleSiyum
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdfTeshaleSiyum
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxGebruGetachew2
 
Pointers and call by value, reference, address in C
Pointers and call by value, reference, address in CPointers and call by value, reference, address in C
Pointers and call by value, reference, address in CSyed Mustafa
 
Fnctions part2
Fnctions part2Fnctions part2
Fnctions part2yndaravind
 
Fundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariFundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariTHE NORTHCAP UNIVERSITY
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxSangeetaBorde3
 

Similar to 3 Function & Storage Class.pptx (20)

Functions
FunctionsFunctions
Functions
 
4th unit full
4th unit full4th unit full
4th unit full
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2
 
Function
FunctionFunction
Function
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
Pointers and call by value, reference, address in C
Pointers and call by value, reference, address in CPointers and call by value, reference, address in C
Pointers and call by value, reference, address in C
 
Function in c
Function in cFunction in c
Function in c
 
Fnctions part2
Fnctions part2Fnctions part2
Fnctions part2
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
Fundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariFundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan Kumari
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
Function in c
Function in cFunction in c
Function in c
 
Functions
FunctionsFunctions
Functions
 

Recently uploaded

Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAbhinavSharma374939
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 

Recently uploaded (20)

Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog Converter
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 

3 Function & Storage Class.pptx

  • 1. VELAMMAL ENGINEERING COLLEGE An Autonomous Institution, Affiliated to Anna University Chennai, & Approved by AICTE Delhi UNIT III FUNCTIONS AND STORAGE CLASSES 1 Velammal Engineering college/Dept. of CSE
  • 2. UNIT-III FUNCTIONS AND STORAGE CLASSES Defining a function – Accessing a function – Function prototypes – Passing arguments to a function – Passing arrays to functions – Function with string - Recursion – Storage classes Velammal Engineering college/Dept. of CSE 2
  • 3. Introduction ▪ A function is a self-contained block of program statements that performs a particular task.
  • 4. Need for functions: ▪ It breaks up a program into easily manageable chunks and makes programs easier to understand. ▪ Improves the reusability of code. ▪ Easy debugging of code. ▪ Different programmers working on one large project can divide the workload by writing different functions.
  • 5. Using functions: ▪ All C programs contain atleast one function, called main() when execution starts. ▪ When a function is called, the code contained in that function is executed. ▪ When the function has finished executing, control returns to the point at which that function was called.
  • 6. Questions: • What is mean by function? • Advantages of functions? Velammal Engineering college/Dept. of CSE 6
  • 8. Function Prototype Declaration: return_datatype function_name(datatype var1, datatype var2, …); ▪ return_datatype : specifies the type of data given back by the function after executing a specific task. ▪ function_name: this is the name given to the function. It allows the same rules as that for any valid variable in C. ▪ datatype var1,...... : specifies the datatype of the variables passed to the function.
  • 9. Rules: ▪The name of the function is global. ▪No function can be defined in another function body. ▪Number if arguments must agree with the number of parameters specified in the prototype. ▪The function return type cannot be an array or a function type.
  • 10. Function Definition: ▪ The collection of program statements in C that describes the specific task done by the function is called function definition. ▪ It consists of ▪ Function header ▪ Function body return_datatype function_name(datatype var1, datatype var2, …) /* Function header */ { /* Function Body */ } ▪ No semicolon in function header. ▪ The list of variables in the function header is also referred to as the formal parameters.
  • 11. Function Call: ▪ Syntax: function_name(variable1, variable2,...); Or var_name = function_name(variable1, variable2,...); ▪ If there are no arguments to be passed in the function, function_name( ); Or var_name = function_name( ); ▪ Information will be passed to the function via special identifiers called arguments or actual parameters and returned via the return statement.
  • 12. Rules for parameters: • The number of parameters in the actual and formal parameter lists must be consistent. • Parameter association in C is positional. • Actual parameters and formal parameters must be of compatible data types. • Actual (input) parameters may be a variable, constant, or any expression matching the type of the corresponding formal parameter.
  • 13. Question: • What are the components of function? Velammal Engineering college/Dept. of CSE 13
  • 14. Program 1: Sum of two numbers #include<stdio.h> int sum(int, int);/*Function declaration*/ void main() { int i,j,k; printf(“Enter the values for i and j”); scanf(“%d %d”,&i, &j); k = sum(i,j); /* Function Call */ printf(“Sum of two values = %d”,k); } int sum(int a, int b) /* Function Definition */ { return(a+b); } Output: Enter the values for i and j 10 20 Sum of two values = 30
  • 15. Passing arguments to a function: ▪ The technique used to pass data to a function is known as parameter passing. ▪ Data are passed to a function using two techniques: 1. Call by value or Pass by value. 2. Call by reference or Pass by reference.
  • 16. n1,n2 – actual parameters a, b – formal parameters • In programming, argument refers to the variable passed to the function. In the above example, two variables n1 and n2 are passed during the function call. • The parameters a and b accepts the passed arguments in the function definition. These arguments are called formal parameters of the function. Velammal Engineering college/Dept. of CSE 16
  • 17. Call by Value mechanism: ▪ Here, a copy of the data is made and the copy is sent to the function. ▪ Since, only copies are passed, the values in the argument remains unchanged. ▪ As only copies of the values held in the arguments are sent to the formal parameters, the function cannot directly modify the arguments passed.
  • 18. An Example of Call by value Mechanism: #include <stdio.h> void swap(int, int); int main() { int x, y; printf("Enter the value of x and yn"); scanf("%d%d",&x,&y); printf("Before Swapping nx = %dty = %dn", x, y); swap(x, y); printf("After Swappingnx = %dty = %dn", x, y); return 0; } void swap(int a, int b) { int temp; temp = b; b = a; a = temp; printf(“Inside Swap function: Values of a and b is %d %dn",a,b); } Output: Enter the value of x and y 50 30 Before Swapping x = 50 y = 30 Inside Swap function: Values of a and b is 30 50 After Swapping x = 50 y = 30
  • 19. Call by reference mechanism: ▪ Here, the address of the data is sent rather than a copy. ▪ In this case, the called function can change the original data in the calling function. ▪ Details will be discussed in the chapter on pointers.
  • 20. Call by reference Velammal Engineering college/Dept. of CSE 20
  • 21. Difference between call by value and call by reference in c No. Call by value Call by reference 1 A copy of the value is passed into the function An address of value is passed into the function 2 Changes made inside the function is limited to the function only. The values of the actual parameters do not change by changing the formal parameters. Changes made inside the function validate outside of the function also. The values of the actual parameters do change by changing the formal parameters. 3 Actual and formal arguments are created at the different memory location Actual and formal arguments are created at the same memory location Velammal Engineering college/Dept. of CSE 21
  • 22. Function Usage in various ways: ▪ Functions can be used in a program in various ways: a. Function that perform operations on their parameters and return a value. b. Function that manipulates information on their parameters and return a value that simply indicates the success or failure of that manipulation. c. Function having no return type that is strictly procedural.
  • 23. Function that perform operations on their parameters and return a value: #include <stdio.h> int GCD(int, int); int main() { int n1, n2, n; printf("Enter two numbers: "); scanf("%d %d",&n1,&n2); n = GCD(n1, n2); printf(“n GCD of %d and %d is %d”,n1, n2,n); return 0; } int GCD(int x, int y) { int result = 1, k = 2; while(k <= x && k <= y) { if(x % k == 0 && y % k == 0) result = k; k++; } return result; }
  • 24. • Example: GCD of the numbers 10 and 12. 10 has for divisors' list: 1,2,5,10 12 has for divisors' list: 1,2,3,4,6,12 The greatest common divisor (of these lists) is 2 (The largest number in all lists). So, GCD(10,12) = 2 Velammal Engineering college/Dept. of CSE 24
  • 25. Function that manipulates information on their parameters and return a value that simply indicates the success or failure of that manipulation. #include <stdio.h> bool isPrime(int); int main() { int n, d = 2; printf("Enter the number: "); scanf("%d",&n); printf(“n Prime factors of %d are n”,n); for (d = 2; d <= n/2; d++) if(n %d == 0 && isPrime(d)) printf(“%dt”,d); return 0; } bool isPrime(int x) { int k; for( k = 2; k <= x/2; k++) if(x % k == 0) return 0; return 1; } Output: Enter the number: 51 Prime factors of 51 are 3 17
  • 26. Function having no return type that is strictly procedural. ❑When we pass the value of a variable to a function, a copy of that value gets assigned to the parameter. ❑Changing the value of the parameter within the called function does not affect the value of the variable in the calling function. ❑But, things are different when an array is passed to a function. What we are actually passing is the memory address of the array. ❑If the called function changes specific entries in the array, these entries remain changed when control gets back to the calling function. ❑So, when arrays or strings are passed to a function, call by value mechanism is not followed.
  • 27. Function having no return type that is strictly procedural. #include <stdio.h> void sort(int [ ], int); int main() { int i; int arr[10] = { 3,2,7,0,6,4,9,8,1,5}; printf(“n The array before sorting:n"); for (i = 0; i < 10; i++) printf(“%dt”,arr[i]); sort(arr,10); printf(“n The array after sorting:n"); for (i = 0; i < 10; i++) printf(“%dt”,arr[i]); return 0; } void sort(int a[ ], int n) { int i,j,temp; for(i = 0; i < n-1; i++) for(j = 0; j < n-i-1; j++) if(a[j] > a[j+1]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } Output: The array before sorting: 3 2 7 0 6 4 9 8 1 5 The array after sorting: 0 1 2 3 4 5 6 7 8 9
  • 28. Difference between call by value and call by reference in c Velammal Engineering college/Dept. of CSE 28
  • 29. Passing Arrays to Functions ❑Arrays can also be the arguments of functions. When an array is passed to a function, the address of the array is passed and not the copy of the complete array. ❑Therefore, when a function is called with the name of the array as the argument, address of the first element in the array is handled over to the function. ❑Since the address of the array is passed, the function has the ability to modify the contents of the array. ❑Therefore, array is not passed to the function by value.
  • 30. Passing arrays as arguments: - Average age of students #include <stdio.h> float avg_age(int [ ], int); int main() { int i, a[50],n; float average; printf(“n How many students?"); scanf(“%d”,&n); printf(“Enter the age of students:n”); for (i = 0; i < n i++) scanf(“%d”,&a[i]); average = avg_age(a,n); printf(“n The average age of students: %fn“, average); return 0; } float avg_age(int b[ ], int n) { int j; float sum = 0.0; for(j = 0; j < n; j++) sum = sum + b[j]; return sum/n; }
  • 31. Passing String to Functions ❑Strings are passed to the functions in the same way as are one- dimensional arrays. /* Function to copy one string into another */ #include <stdio.h> void string_copy(char [ ], char [ ]); int main() { char a[100]; /* Source String */ char b[100]; /* Destination String */ printf(“n Input Source String"); scanf(“%[^n]”, a); string_copy(b,a); printf(“n Destination String: %sn“,b); return 0; } void string_copy(char d[ ], char s[ ]) { int i = 0; printf(“n Source String: %sn“,s); for( i = 0; s[i] != ‘0’; i++) d[i] = s[i]; }
  • 32. Passing Multidimensional Arrays to Functions ❑Multidimensional arrays are also allowed to be passed as arguments to functions. ❑Ex. : Matrix ❑Here, first dimension can be omitted in formal parameter. ❑Ex.: int yield(int a[ ][4], int index);
  • 33. Lifetime: ❑Lifetime is the period during execution of a program in which a variable or a function exists.
  • 34. Local Variables ❑Variables declared within the function body are called local variables. ❑They have local lifetime. ❑Local variables are automatically created at the point of their declaration within the function body and are usable inside the function body. ❑They only exist inside the specific function that creates them. They are unknown to other functions and to the main program. ❑The existence of the local variables ends when the function completes its task & returns to the calling point. ❑They are recreated each time a function is executed or called.
  • 35. Global Variables ❑Variables declared outside of all the functions of a program and accessible by any of these functions are called global variables. ❑The existence and region of usage of these variables are not confined to any specific function body. ❑Global variables are created at the beginning of program execution and remain in existence all through the period of the execution of the program. ❑They are known to all functions in the program and can be used by these functions as many times as may be required. ❑They do not get recreated if the function is recalled.
  • 36. SCOPE ▪The region of the program over which the declaration of an identifier is accessible is called the scope of the identifier. ▪The scope relates to the accessibility, the period of existence, and the boundary of usage of variables declared in a program. ▪Scopes can be of four types. ▪Block ▪File ▪Function ▪Function prototype
  • 37. Block scope • This means that the identifier can only be used in the block in which it is declared. • These variables are created at the point of their declaration inside the block and cease to exist outside it. • Outside the block, these variables are unknown and non-existent. • Example: Velammal Engineering college/Dept. of CSE 37
  • 38. Function scope • This applies only to labels. Normally labels are used with goto statement. • It simply means that labels can be used anywhere within the function in which they are defined. • This includes use before definition. Velammal Engineering college/Dept. of CSE 38
  • 39. File scope • This means that the identifier can be used anywhere in the current file after the declaration of the identifier. • This applies to functions and all variables declared outside functions. • File scope variable is also known as global variable. Velammal Engineering college/Dept. of CSE 39
  • 40. Function prototype scope • In order to improve readability and understandabilty, function prototypes are usually written with ‘dummy’ variable names. • For example double max(double x, double y); • The identifiers ‘x’ and ‘y’ have function prototype scope, which terminates at the end of the prototype. Velammal Engineering college/Dept. of CSE 40
  • 41. Recursion ❑A recursive function is one that calls itself directly or indirectly to solve a smaller version of its task until a final call which does not require a self-call. ❑A function that calls itself is known as a recursive function. And, this technique is known as recursion.
  • 42. Recursion • To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch makes the recursive call, and other doesn't. • Example: Sum of Natural Numbers Using Recursion Velammal Engineering college/Dept. of CSE 42
  • 43. Example: Sum of Natural Numbers Using Recursion Velammal Engineering college/Dept. of CSE 43
  • 44. Recursion ❑The following are necessary for implementing recursion: ✔Decomposition into smaller problems of same type. ✔Recursive calls must diminish problem size. ✔Necessity of base case. ✔Base case must be reached. ✔It acts as a terminating condition. ✔It is the building block to the complete solution.
  • 45. Base Case ❑An instance of a problem the solution of which requires no further recursive calls is known as the base case. ❑Every recursive algorithm requires atleast one base case in order to be valid.
  • 46. Recursive function to find factorial of a number #include <stdio.h> int factorial(int); int main() { int n, res; printf(“Enter the number”); scanf(“%d”,&n); res = factorial(n); printf(“The factorial of %d is %d”,n,res); return 0; } int factorial(int num) { if(num == 0) return 1; else return(num * factorial(num - 1)); } O/P: Enter the number 4 The factorial of 4 is 24.
  • 47. Types of Function • There are two types of functions namely • Library Functions: Function defined are included with C compilers are known as library functions. These functions are built-in, pre-compiled and ready to use. Example: printf(),sqrt() • User Defined Functions: Functions defined by an end programmer is known as user defined function. A programmer can define any number of function depending on the need. Example: add() Velammal Engineering college/Dept. of CSE 47
  • 48. Function usage based on parameters and return type • Based on the prototype, there can be 4 different types of user- defined functions, they are: • Function with no arguments and no return value. • Function with no arguments and a return value. • Function with arguments and no return value. • Function with arguments and a return value. Velammal Engineering college/Dept. of CSE 48
  • 49. Lifetime: ❑Lifetime is the period during execution of a program in which a variable or a function exists.
  • 50. Local Variables ❑Variables declared within the function body are called local variables. ❑They have local lifetime. ❑Local variables are automatically created at the point of their declaration within the function body and are usable inside the function body. ❑They only exist inside the specific function that creates them. They are unknown to other functions and to the main program. ❑The existence of the local variables ends when the function completes its task & returns to the calling point. ❑They are recreated each time a function is executed or called.
  • 51. Global Variables ❑Variables declared outside of all the functions of a program and accessible by any of these functions are called global variables. ❑The existence and region of usage of these variables are not confined to any specific function body. ❑Global variables are created at the beginning of program execution and remain in existence all through the period of the execution of the program. ❑They are known to all functions in the program and can be used by these functions as many times as may be required. ❑They do not get recreated if the function is recalled.
  • 52. Storage Class Specifiers for Variables • Variables are declared by the type of data they can hold • The name of a variable is associated with a memory location within the computer where the value assigned to the variable is stored in the form of bits. • C provides four storage class specifiers to indicate where the variables • would be stored • how long they would exist • what would be their region of existence • what would be the default values • Four storage class specifiers are • Automatic • External • Register • Static • Storage class specifier precedes the declaration statement for a variable. • The general form of the variable declaration statement with storage class specifier is given as follows: • storage_class_specifier data_type variable_name; Velammal Engineering college/Dept. of CSE 52
  • 53. The storage class – auto • By default, all variables declared within the body of any function are automatic. • To explicitly specify variable as automatic storage class keyword “auto” is used in the declaration • For example, the following declaration statement within a function body • auto char any_alpha; Ex: auto int a=10; • Variable stored : primary memory of the computer • Scope : limited within the function body • Existence : Vanishes when the function completes its specific task and returns to the invoked main program • Note – 1. If function body does not include the keyword auto, such declared variables are implicitly specified as belonging to the automatic storage class 2. Local variables declared within nested blocks in a function belong by default to the automatic storage class Velammal Engineering college/Dept. of CSE 53
  • 54. Example 2 : C program that demonstrates the use of the automatic storage class variable #include <stdio.h> int main(void) { auto int a =5; printf(“n a = %d”,a); { int a = 10; printf(“n a = %d”,a); printf(“n i = %d”,i); } printf(“n a = %d”,a); return 0; } Output a = 5 a = 10 i = 4199232 a = 5 Velammal Engineering college/Dept. of CSE 54
  • 55. The storage class – register • Values stored in registers of the CPU are accessed in much lesser time than those stored in the primary memory. • To allow the fastest access time for variables, the register storage class specifier is used. • The keyword for this storage class is “register” • For example, the following declaration statement within a function body • register char any_alpha; Ex: register int a=10; • In most C compilers, the register specifier can only be applied to int and char type variables; however, ANSI C has broadened its scope. Velammal Engineering college/Dept. of CSE 55
  • 56. The storage class – register • Variable stored : registers of the CPU • Scope : Restricted within the region of a function or a block where it has been declared • Existence : exists as long as the function or block remains active. • Default value : unknown, which is interpreted as garbage. • Note – 1. Storage class of a global variable cannot be specified as register. 2. Arrays cannot be stored in a registers but they may still receive preferential treatment by the compiler depending on C compiler and the operating system under which it is running Velammal Engineering college/Dept. of CSE 56
  • 57. The storage class – register Note – 3. Global variables with register storage class are not allowed. 4. In C, it is not possible to obtain the address of a register variable by using ‘&’ operator. 5. In addition, the only storage class specifier that can be used in a parameter declaration is register. Velammal Engineering college/Dept. of CSE 57
  • 58. Example 1 : C program that demonstrates register variables #include <stdio.h> int main() { int m1 = 5; register int m2 = 10; printf("The value of m1 : %d ",m1); printf("nThe value of m2 : %d ",m2); return 0; } Output The value of m1 : 5 The value of m2 : 10 Velammal Engineering college/Dept. of CSE 58
  • 59. Example 2 : C program that demonstrates register variables #include <stdio.h> /* function declaration */ main() { register int weight; int *ptr=&weight ;/*it produces an error when the compilation occurs ,we cannot get a memory location when dealing with CPU register*/ } Output error: address of register variable 'weight' requested Velammal Engineering college/Dept. of CSE 59
  • 60. The storage class – static • Two kinds of variables are allowed to be specified as static variables: • local variables (internal static variables) • global variables (external static variables) • To specify a local variable as static, the keyword “static” precedes its declaration statement • For example, the following declaration statement within a function body • static int beta; Velammal Engineering college/Dept. of CSE 60
  • 61. The storage class – static Static local variable • Variable stored : permanent storage location in the primary memory • Scope : is usable within functions or blocks where it is declared and preserves its previous value held by it between function calls or between block re-entries • Existence : once a function is invoked, the static local variable retains the value in it and exists as long as the main program is in execution • Default value : zero Static global variable • Variable stored : stored in the primary memory • Scope : accessible by all functions in the program file where these variables exist and are declared. • not available to functions defined earlier in the same file or not accessible to functions defined in other files although these may use the extern keyword • Existence : exist throughout the period of the main program execution • Default value : zero Velammal Engineering college/Dept. of CSE 61
  • 62. Example1 : C program that demonstrates the use of the static variables and functions #include <stdio.h> int main() { void show(void); printf(“n First Call of show()”); show(); printf(“n Second Call of show()”); show(); printf(“n Third Call of show()”); show(); return 0; } void show(void) { static int i; printf(“n i=%d”,i); i++; } Output First Call of show() i=0 Second Call of show() i=1 Third Call of show() i=2 Velammal Engineering college/Dept. of CSE 62
  • 63. Example 2 : C program that demonstrates the use of the static variables and functions #include <stdio.h> void func(void); static int count = 5; /* global variable */ int main() { while(count--) { func(); } return 0; } /* function definition */ void func( void ) { static int i = 5; /*local static variable */ i++; printf("i is %d and count is %dn", i, count); } Output i is 6 and count is 4 i is 7 and count is 3 i is 8 and count is 2 i is 9 and count is 1 i is 10 and count is 0 Velammal Engineering college/Dept. of CSE 63
  • 64. The storage class – extern • When C program is large, it can be broken up into smaller programs. • After compiling, each program file can be joined together to form the large program. • These small program modules that combine together may need some variables that are used by all of them. • External storage class variable are accessible to all the small program modules • These variables are global to all the small program modules that are formed as separate files. • The keyword “extern” for declaring such global variables • For example, the following declaration statement within a function body • extern int zeta; • Such global variables are declared like any other variable in one of the program modules while the declaration of these variables is preceded with the keyword extern in all other combining program modules (may be a function or a block). Velammal Engineering college/Dept. of CSE 64
  • 65. The storage class – extern • Variable stored : primary memory • Scope : Accessible by small program modules that form the large program • Existence : exists as long as the program is in execution and their existence does not terminate upon the exit of a function or a block or a program module from its state of execution • Default value : zero Velammal Engineering college/Dept. of CSE 65
  • 66. /* Program file: pgm1.c */ #include <stdio.h> #include “pgm2.c” /*link pgm2.c */ int i; /*external/global decl*/ void show(void);/*fn prototype*/ int main() { i=10; show();/*call to fn in pgm2.c*/ printf(“n Value of i in pgm1.c=%d ”,i); return 0; /* Program file : pgm2.c */ extern int i; /*fn definition of show()*/ void show() /*fn header */ { printf(“n Value of i in pgm2.c=%d”,i); } Velammal Engineering college/Dept. of CSE 66 Output Value of i in pgm2.c=10 Value of i in pgm1.c=10
  • 67. /* Program file: pgm1.c */ #include <stdio.h> #include “pgm2.c” /*link pgm2.c */ int i; /*external/global decl*/ void show(void); /*fn prototype */ int main() { show(); /*call to fn in pgm2.c */ printf(“n Value of i in pgm1.c=%d”,i); return 0; } /* Program file : pgm2.c */ extern int i; /*fn definition of show()*/ void show() /*fn header ***/ i = 20; printf(“n Value of i in pgm2.c=%d”,i); } Velammal Engineering college/Dept. of CSE 67 Output Value of i in pgm2.c=20 Value of i in pgm1.c=20
  • 69. Storage Class Specifiers for Functions • The only storage class specifiers that may be assigned with functions are ✔ extern ✔ static • The extern signifies that the function can be referenced from other files- that is,the function name is exported to the linker. • The static signifies that the function cannot be referenced from other files- that is the function name is not exported to the linker. • If no storage class appears in a function definition, extern is presumed Velammal Engineering college/Dept. of CSE 69
  • 70. Linkage • An identifier’s linkage determines which of the references to that identifier refer to the same object. • An identifier’s linkage is determined by whether it appears inside or outside a function, whether it appears in a declaration of a function (as opposed to an object), its storage-class specifier, and the linkage of any previous declarations of the same identifier that have file scope Velammal Engineering college/Dept. of CSE 70
  • 71. Linkage • C defines three types of linkages – external, internal and no linkage • In general, • Functions and global variables have external linkage(available to all files in a program. • Identifiers with file scope declared as static have internal linkage(known only within the file in which they are declared) • Local identifiers have no linkage and are therefore known only within their own block. • Two declarations of the same identifier in a single file that have the same linkage, either internal or external, refer to the same object. • The same identifier cannot appear in a file with both internal and external linkage. Velammal Engineering college/Dept. of CSE 71
  • 72. /* Program file: animals.c */ #include <stdio.h> static int animals = 8; const int i = 5; int call_me(void) { printf("%d %d", i, animals); } /* Program file : feed.c located in a different translation unit*/ #include <stdio.h> int main() { call_me(); animals = 2; printf("%d", animals); return 0; } Velammal Engineering college/Dept. of CSE 72 Output 5 8 2 Example : C code to illustrate Internal Linkage
  • 73. /* Program file: animals.c */ #include <stdio.h> void foo() { int a; extern int b; // line 1 } void bar() { int c; c = b; // error } int main() { foo(); bar(); } Velammal Engineering college/Dept. of CSE 73 Output Error: 'b' was not declared in this scope Example : C code to illustrate External Linkage
  • 74. /* Program file: animals.c */ #include <stdio.h> int x = 10; int z = 5; int main() { extern int y; // line 2 extern int z; printf("%d %d %d", x, y, z); } int y = 2; Velammal Engineering college/Dept. of CSE 74 Output 10 2 5 Example : C code to illustrate External Linkage
  • 75. Thank you Velammal Engineering college/Dept. of CSE 75