Professional Documents
Culture Documents
Functions
In c, we can divide a large program into the basic building
blocks known as function.
A block of code which performs specific tasks.
The function contains the set of programming statements
enclosed by {}.
A function can be called multiple times to provide reusability
and modularity to the C program.
Once a function execution is completed, the control return to
the place from where the function was called.
The function is also known as procedure or subroutine in other
programming languages.
Advantages of functions
By using functions, we can avoid rewriting same logic/code
again and again in a program.
We can call C functions any number of times in a program and
from any place in a program.
We can track a large C program easily when it is divided into
multiple functions.
Reusability is the main achievement of C functions.
However, Function calling is always a overhead in a C
program.
Types of functions
Built-in Functions
#include<stdio.h>
#include<conio.h>
void sum(); //Function declaration
void main()
{
sum(); //Function Call
getch();
}
void sum() //Function definition
{
int a,b;
printf(“\nEnter two integers:”);
scanf(“%d%d”,&a,&b);
printf(“\nsum=%d”,a+b);
}
function without arguments and with return value
#include<stdio.h>
#include<conio.h>
int sum(); //Function declaration
void main()
{
int x;
x=sum(); //Function Call
printf(“\nsum=%d”,x);
getch();
}
int sum() //Function definition
{
int a,b;
printf(“\nEnter two integers:”);
scanf(“%d%d”,&a,&b);
return(a+b);
}
function with arguments and without return value
#include<stdio.h>
#include<conio.h>
void sum(int,int); //Function declaration
void main()
{
int a,b;
printf(“\nEnter two integers:”);
scanf(“%d%d”,&a,&b);
sum(a,b); //Function Call
getch();
}
void sum(int a,int b) //Function definition
{
printf(“\nsum=%d”,a+b);
}
function with arguments and with return value
#include<stdio.h>
#include<conio.h>
void main()
int a,b,x;
scanf(“%d%d”,&a,&b);
printf(“\nsum=%d”,a+b);
getch();
return(a+b);
}
Parameter Passing methods
There are two methods to pass the data into the function
in C language, i.e., call by value and call by reference.
Call by value
#include<stdio.h>
#include<conio.h>
void main()
{
int a; //auto
char b;
float c;
printf("%d %c %f",a,b,c);
getch();
}
Static
#include<stdio.h>
#include<conio.h>
int a;
int main()
{
extern int a;
printf("%d",a);
getch();
}
Example
extern int a;
int a = 10;
#include <stdio.h>
int main()
{
printf("%d",a);
}
int a = 20; // compiler will show an error at this line
Storage Storage Default Scope Lifetime
classes place value
auto RAM Garbage Local Within function
Value
extern RAM Zero Global Till the end of the
main program Maybe
declared anywhere in
the program
static RAM Zero Local Till the end of the
main program, Retains
value between
multiple functions call
register Register Zero Local Within function