Functions in C
Functions in C
Functions
● A function is a block of codes or sub programs with a set of statements that perform
some specific task or coherent task when it is called by other functions including
main
● Any ‘C’ program contain at least one function i.e main().
● There are basically two types of functions:
1. Library function
2. User defined function
● The user defined functions defined by the user according to its requirement.
● Library defined function can’t be modified, it can only read and can be used. These
function are supplied with every C compiler
2
What is a Function
4
Function declaration
● Function declaration is also known as function prototype.
● It informs the compiler about three things-
1.name of the function
2.number and type of arguments received by the function
3.the type of value returned by the function.
● While declaring the name of the argument is optional and the function prototype
always terminated by the semicolon.
5
Function Call
● When the function gets called by the calling function then that is - function call.
● The arguments that are used inside the function call are called actual arguments/
parameters and these are the original values and copy of these are actually sent to
the called function
● Example:-
result = add3num(n1,n2,n3); //actual arguments – n1,n2,n3
6
Function definition
● Function definition consists of the code of the function - what function is doing what are
its inputs and what are its output
● Syntax:-
Return_value_Datatype function_name(datatype1 arg1, datatype2 arg2, …) /*function
header*/
{
Local variable declaration;
Statement (s); /* function body */
return (value);
}
● The return_value_Datatype denotes the datatype of the value that function returns
● The arguments in the function definition are known as formal arguments/parameters
● The body of the function is the statements or block which consists of local variable
declaration, one or more executable statements and optional return statement. 7
User Defined Functions arguments list
● Example:
Return_type function_name(datatype 1 arg 1, datatype2 arg2, …)
● Function call - where the function is used void main() /* calling function*/
{
int n1, n2, n3, result;
printf(“…”);
scanf(“…”);
result = add3num(n1,n2,n3);
printf(“…”);
}
8
Return Statement
● It is used to return a value to the calling function.
● Not more than one value can be returned through the return statement.
● It can be used as return value or return(expression);
● Ex:-
return;
return (a); or return a;
return (a*b+c/d);
return (add3num(a,b,c));
return a,b; invalid
● Here the 1st return statement is used to terminate the function without returning any
value
● We can use a function call statement in the return statement
9
Parameters/Arguments
● Actual arguments
● The arguments which are mentioned or used inside the function call is knows as actual argument and
these are the original values
● It can be written as variable, constant, expression or any function call like
Functionname (x);
Functionname (x, 20, 30);
Functionname (a*b, 15, a, c*d);
Functionname(2, d, sum(a, b));
● Formal Arguments
● The arguments that are mentioned in function definition are called formal arguments or dummy
arguments , that just hold the copies of the actual parameter values that are sent by the calling function
through the function call.
● These arguments are like other local variables which are created when the function call starts and
destroyed when the function ends.
● Order number and type of actual arguments in the function call should be match with the order number10
and type of the formal arguments.
# include<stdio.h>
int add3num(int, int, int); // Optional – Prototype – FUNCTION DELARACTION
void main( ) // Calling Function
{
int n1, n2, n3, result; Actual parameters n1, n2, n3
printf(“Enter 3 numbers”); n1 =
20
scanf(“%d%d%d”, &n1, &n2, &n3);
result = add3num(n1,n2,n3); // FUNCTION CALL n2 =
25
printf(“Sum of 3 numbers = %d”, result);
} n3 =
14
● By using function large and difficult program can be divided in to sub programs
● and solved.
● When some task has to be performed repeatedly or some code is to be used more
than once at different place in the program, then function avoids this repetition or
rewritten over and over.
● Due to reducing size, modular function is easy to modify and test
● Identifying and Debugging errors is easier and faster
● A function can be called any number of times.
● A function can call itself again and again and this process is called recursion.
● A function can be called from other function but a function can’t be defined in
another function
12
Types of Functions
● Functions are categorized based on the argument passing and return value
1. Passing parameter and return value
2. Passing parameter and No return value
3. No passing parameter and return value
4. No passing parameter and No return value
void main() void main() void main() void main()
{ { { {
int n1, n2, n3, result; int n1, n2, n3, result; …….. ……..
printf(“…”); printf(“…”); result = add3num( ); add3num();
scanf(“…”); scanf(“…”); …….. ……..
result = add3num(n1,n2,n3); add3num(n1,n2,n3); } }
printf(“…”); }
}
int add3num( ) void add3num()
void add3num(int a, int b, int c) { {
int add3num(int a, int b, int c) { int a,b,c ,sum; int a,b,c ,sum;
{ int sum; printf(“…”); printf(“…”);
int sum; sum = a+b+c; scanf(“…”); scanf(“…”);
sum = a+b+c; printf(“…”); sum = a+b+c; sum = a+b+c;
return sum; return; return sum; printf(“…”);
} } } return ;
}
14
Passing parameters to functions
● There are two way through which we can pass the arguments/parameters to the
function
● call by value
● call by reference
15
Call by value
● In the call by value copy of the actual argument is passed to the formal argument
and the operation is done on formal argument.
● When the function is called by ‘call by value’ method, it doesn’t change the value of
the actual argument.
● Changes made to formal argument are local inside the called function, so when the
return statement is executed the formal parameters are deleted or terminated in
memory.
void main() /* calling function*/ n1 = a = 20 21
{ 20 int add3num(int a, int b, int c)
int n1, n2, n3, result; {
printf(“…”); int sum; b = 25 26
scanf(“…”); n2 = sum = a+b+c;
a++; b++; c++;
result = add3num(n1,n2,n3); 25 return sum; c = 14 15
printf(“…”);
} }
n3 = Sum = 59
14
16
Call by Reference
● Instead of passing the value of variable, address/ reference is passed and the
function operates on the contents of that address.
● Any changes made to formal argument is reflected on the actual argument, as both
are referring to the same location.
18
Scope of Variables ● Variables can be either local or global
20
#include <stdio.h> result = 0 59
int result=0;
void main() /* calling function*/
{
int a, b, c; a = 20
printf(“…”);
b = 25
scanf(“…”);
result = add3num(a,b,c); c = 14
printf(“…”);
}
When you want it to be done, you go to the service station and say, “It’s time, do it now”.
You don’t need to give instructions, because the mechanic knows his job. You don’t need
to be told when the job is done.
You assume the bike would be serviced in the usual way, the mechanic does it and that’s
that.
Any C program contains at least one function.
If a C program contains more than one function, then one (and only one) of these
functions must be main( ), because program execution always begins with main( ).
Each function in a program is called in the sequence specified by the function calls in
main( ).
After each function has done its thing, control returns to main( ).
The built-in-function are also called library function or Standard Function. These
functions are provided by programmer.
Function prototypes Provides the compiler with the description of functions that will be used later in
the program
Its define the function before it been used/called
Function prototypes need to be written at the beginning of the program.
The function prototype must have:
A return type indicating the variable that the function will be return
Syntax for Function Prototype
return-type function_name(arg-type name-1, ,arg-type name-n);
Function definition
int get_menu_choice(void);
Function return types Can be any of C's data type:
char
int
float
long.
Examples:
int func1(...) /* Returns a type int. */
The arguments used in the function declaration are referred as formal arguments.
They are simply formal variables that accept or receive the values supplied by the
calling function.
The number of actual and formal arguments and their data types should be same
Example:
// block cope
Function Scope/Local variable
Program Scope/Global variable
● Storage class defines the scope (visibility) and lifetime of variables and/or
functions declared within a C program.
● The storage class of a function or a variable determines the part of memory
where storage space will be allocated for that variable or function.
● It specifies how long the storage allocation will continue to exist for that
function or variable.
● It specifies whether the variable will be automatically initialized to zero or to
any indeterminate value.
● C supports four storage classes: automatic, register, external, and static.
1. auto
● Extern storage class simply tells us that the variable is defined elsewhere
and not within the same block where it is used. Basically, the value is
assigned to it in a different block and this can be overwritten/changed in a
different block as well.
● So an extern variable is nothing but a global variable initialized with a
legal value where it is declared in order to be used elsewhere. It can be
accessed within any function/block.
● Also, a normal global variable can be made extern as well by placing the
‘extern’ keyword before its declaration/definition in any function/block.
File1.c File2.c
3. register
register int x;
4. static
● The difference between an auto variable and a static variable is that the static
variable when defined within a function is not re-initialized when the function is
called again and again.
● It is initialized just once and further calls of the function share the value of the static
variable. Hence, the static variable inside a function retains its value during various
calls.
static int x = 10;
Static storage class
Comparison of storage classes
RECURSIVE FUNCTIONS
● 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.
● Every recursive solution has two major cases.
●Base case
●Recursive case
To calculate n!
● For the factorial function
● Base case is when n = 1, because if n= 1, the result will be ‘1’ as
1! = 1.
● Recursive case of the factorial function will call itself but with a smaller
value of n, this case can be given as
factorial(n) =n * factorial(n — 1)
Factorial
program
From the aforegiven example, let us analyse the basic steps
of a recursive program.
● Step 1: Specify the base case which will stop the function from making a
call to itself
● Step 2: Check to see whether the current value being processed matches
with the value of the base case. If yes, process and return the value
● Step 3: Divide the problem into smaller or simpler sub problems.
● Step 4: Call the function from the sub-problems.
● Step 5: Combine the results of the sub-problems.
● Step 6: Return the result of the entire problem
Greatest Common Divisor
void main()
int a, b;
scanf("%d%d", &a,&b);
}
#include<stdio.h>
void main()
int a,b;
scanf("%d%d", &a,&b);
sum(a, b);