Understanding Functions in C Programming
Understanding Functions in C Programming
1
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Introduction
Function
• A program segment that carries out a specific, well-defined task.
• Examples
• A function to find the gcd of two numbers
• A function to find the largest of n numbers
2
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Function Control Flow
Code
Execution
void print_banner ( )
{ int main () print_banner {
printf(“********\n”); {
…
} }
print_banner ();
…
print_banner {
print_banner ();
int main ( )
{ } }
. . .
print_banner ( ) ;
. . .
print_banner ( ) ; If function A calls function B:
}
A : calling function / caller function
B : called function
3
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Why Functions?
Functions allow one to develop a program in a modular fashion.
• Codes become readable
• Codes become manageable to debug and maintain
Write your own functions to avoid writing the same code segments multiple times
• If you check several integers for primality in various places of your code, just write a single
primality-testing function, and call it on all occasions
4
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Use of functions: Area of a circle
#include <stdio.h>
int main()
{
float radius, area;
5
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Use of functions: Area of a circle
#include <stdio.h>
6
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Defining a Function #include <stdio.h>
The first line contains the return-value-type, the function name, and int main()
optionally a set of comma-separated arguments enclosed in ( ). {
float radius, area;
• Each argument has an associated type declaration.
• The arguments are called formal arguments or formal parameters.
scanf (“%f”, &radius);
Example:
area = myfunc (radius);
float myfunc (float r) printf (“\n Area is %f \n”, area);
int gcd (int A, int B) return 0;
}
7
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Calling a function #include <stdio.h>
• Called by specifying the function name and parameters in
an instruction in the calling function.
/* Function to compute the area of a
• When a function is called from some other function, the circle */
float myfunc (float r)
corresponding arguments in the function call are called
{
actual arguments or actual parameters. float a;
a = 3.14159 * r * r;
• The function call must include a matching actual return a;
parameter for each formal parameter. }
• Position of an actual parameters in the parameter list in
int main()
the call must match the position of the corresponding {
formal parameter in the function definition. float radius, area;
8
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Function Prototypes: declaring a function
Usually, a function is defined before it is called.
• main() is usually the last function in the program written.
• Easy for the compiler to identify function definitions in a single scan through the file.
Some prefer to write the functions after main(). There may be functions that call each other.
• Must be some way to tell the compiler what is a function when compilation reaches a function call.
• Function prototypes are used for this purpose
• Only needed if function definition comes after a call to that function.
• Function prototypes are usually written at the beginning of a program, ahead of any functions (including main()).
• Prototypes must specify the types. Parameter names are optional (ignored by the compiler).
• Examples: int gcd (int , int );
void div7 (int number);
• Note the semicolon at the end of the line.
• The parameter name, if specified, can be anything; but it is a good practice to use the same names as in the
function definition.
9
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example:
Function prototype / declaration
#include <stdio.h>
int sum( int, int );
This program needs a function prototype or
int main( )
function declaration since the function call
{
comes before the function definition.
int x, y;
scanf(“%d%d”, &x, &y);
printf(“Sum = %d\n”, sum(x, y));
return 0;
Function call
}
10
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Return value
• A function can return a single value • Sometimes a function is not meant for returning anything
Using return statement • Such functions are of type void
• Like all values in C, a function return value has a type
• The return value can be assigned to a variable in the Example: A function which prints if a number is divisible by 7
calling function or not.
11
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
The return statement
In a value-returning function, return does two distinct void compute_and_print_itax ()
things: {
float income;
• Specify the value returned by the execution of the scanf (“%f”, &income);
function. if (income < 50000) {
• Terminate the execution of the called function and printf (“Income tax = Nil\n”);
transfer control back to the caller function. return; /* Terminates function execution */
}
A function can only return one value. if (income < 60000) {
printf (“Income tax = %f\n”, 0.1*(income-50000));
• The value can be any expression matching the return return; /* Terminates function execution */
type. }
• It might contain more than one return statement. if (income < 150000) {
printf (“Income tax = %f\n”,0.2*(income-60000)+1000);
return ; /* Terminates function execution */
In a void function:
}
• "return” is optional at the end of the function body. printf (“Income tax = %f\n”,0.3*(income-150000)+19000);
• "return” may also be used to terminate execution of }
the function explicitly before reaching the end.
• No return value should appear following “return”.
12
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Another Example: What is happening here?
int main()
int prime (int x)
{
{
int numb, flag, j=3;
int i, test;
scanf(“%d”,&numb);
i=2, test =0;
while (j <= numb) {
while ((i <= sqrt(x)) && (test ==0))
flag = prime(j);
{
if (flag == 0)
if (x%i==0) test = 1;
printf( “%d is prime\n”, j );
i++;
j++;
}
}
return test;
return 0;
}
}
13
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Tracking the flow of control
int main() PROGRAM OUTPUT
5
{
numb = 5
int numb, flag, j=3;
int prime(int x)
scanf(“%d”,&numb); Main, j = 3
{
In function, x = 3
printf(“numb = %d \n”,numb); int i, test;
Returning, test = 0
i = 2; test = 0;
while (j <= numb) Main, flag = 0
3 is prime
{ printf(“In function, x = %d \n”,x);
while ((i <= sqrt(x)) && (test == 0))
printf(“\nMain, j = %d\n”,j); Main, j = 4
{
In function, x = 4
flag = prime(j); if (x%i == 0) test = 1;
Returning, test = 1
i++;
printf(“Main, flag = %d\n”,flag); } Main, flag = 1
if (flag == 0) printf(“%d is prime\n”,j); printf(“Returning, test = %d \n”,test);
Main, j = 5
j++; return test; In function, x = 5
} } Returning, test = 0
return 0; Main, flag = 0
5 is prime
}
14
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Nested Functions
A function cannot be defined within another function. It can be called within another function.
• All function definitions must be disjoint.
15
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example: main( ) calls ncr( ), ncr( ) calls fact( )
16
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Local variables
A function can define its own local variables.
The local variables are known (can be accessed) only within the function in which they are
declared.
• Local variables cease to exist when the function returns.
• Each execution of the function uses a new set of local variables.
Parameters are also local.
/* Find the area of a circle with diameter d */
double circle_area (double d) parameter
{
double radius, area;
radius = d/2.0; local variables
area = 3.14*radius*radius;
return (area);
}
17
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Revisiting nCr
18
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Scope of a variable
• Part of the program from which the value of the variable can be used (seen).
19
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
What happens here?
#include <stdio.h>
int A; /* This A is a global variable */
int main( )
{
A = 1;
myProc( );
A=2
printf ( "A = %d\n", A );
return 0;
Scope of }
global A
void myProc( )
{
A = 2;
20
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Local Scope replaces Global Scope
#include <stdio.h>
int A; /* This A is a global variable */
int main( )
{
A = 1;
myProc( );
printf ( "A = %d\n", A ); A=1
return 0;
}
Scope of
global A void myProc( )
{
int A = 2; /* This A is a local variable */
21
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Parameter Passing
When the function is called, the value of the actual parameter is copied to the formal parameter
parameter passing
int main ()
{ . . . double area (double r)
double radius, a; {
. . . return (3.14*r*r);
a = area(radius); }
. . .
}
22
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Parameter Passing by Value in C
Used when invoking functions
Call by reference
• Passes the address of the original argument to a called function.
• Execution of the function may affect the original argument in the calling function.
• Not directly supported in C, but supported in some other languages like C++.
• In C, you can pass copies of addresses to get the desired effect.
23
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Parameter passing and return: 1
int main()
{
int a=10, b;
printf (“Initially a = %d\n”, a);
b = change (a);
printf (“a = %d, b = %d\n”, a, b); Output
return 0;
Initially a = 10
}
Before x = 10
int change (int x) After x = 5
{ a = 10, b = 5
printf (“Before x = %d\n”,x);
x = x / 2;
printf (“After x = %d\n”, x);
return (x);
}
24
24 INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Parameter passing and return: 2
int main()
{
int x=10, b;
printf (“M: Initially x = %d\n”, x);
b = change (x);
printf (“M: x = %d, b = %d\n”, x, b); Output
return 0;
M: Initially x = 10
}
F: Before x = 10
int change (int x) F: After x = 5
{ M: x = 10, b = 5
printf (“F: Before x = %d\n”,x);
x = x / 2;
printf (“F: After x = %d\n”, x);
return (x);
}
25
25 INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Parameter passing and return: 3
int main()
{
int x=10, y=5;
Output
printf (“M1: x = %d, y = %d\n”, x, y);
interchange (x, y); M1: x = 10, y = 5
printf (“M2: x = %d, y = %d\n”, x, y); F1: x = 10, y = 5
return 0; F2: x = 5, y = 10
} M2: x = 10, y = 5
void interchange (int x, int y)
{
int temp;
printf (“F1: x = %d, y = %d\n”, x, y);
temp= x; x = y; y = temp;
printf (“F2: x = %d, y = %d\n”, x, y); How do we write an interchange function?
(will see later)
}
26
26 INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Passing Arrays to a Function
27
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
How to pass arrays to a function?
An array name can be used as an argument to a function.
• Permits the entire array (not exactly) to be passed to the function.
• The way it is passed differs from that for ordinary variables.
Rules:
• Function definition: corresponding formal argument is declared by writing the array name followed by
a pair of empty brackets.
f ( int A[] )
{
...
}
• Function call: the array name must appear by itself as argument, without brackets or subscripts.
f(A), f(B)
28
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
int main()
{
int n;
We can also write float list[100], avg;
:
float x[100] avg = average(n,list);
The compiler completely :
ignores the size 100. }
You can pass arrays of any size float average(int a, float x[])
to the function. There is no {
obligation that only an array of :
size 100 has to be passed. sum = sum + x[i];
}
29
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example: Minimum of a set of numbers
#include <stdio.h> int minimum(int x[], int size)
int minimum (int x[], int y); {
int i, min = 99999;
int main()
{ for (i=0;i<size;i++)
int a[100], i, n; if (min > x[i])
min = x[i];
scanf (”%d”, &n); return (min);
for (i=0; i<n; i++) }
scanf (”%d”, &a[i]);
30
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
The Actual Mechanism
When an array is passed to a function, the values of the array elements are not passed
to the function.
• The array name is interpreted as the address of the first array element.
• The formal argument therefore becomes a pointer to the first array element.
• When an array element is accessed inside the function, the address is calculated
using the formula stated before.
• Changes made to the array elements inside the called function are also reflected
in the calling function.
31
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Parameters are passed in C using call-by-value.
Passing the starting address when an array is sent as argument simulates call-by-reference.
Basically what it means:
• If a function changes the elements of an array that is passed as argument, these changes will be made
to the original array that is passed to the function.
• This does not apply when an individual element of an array is passed as argument.
void f ( int A[], int B )
{
A[2] = 10;
B = 10;
}
int main ()
{
int A[] = {1,2,3,4,5}, B[] = {1,2,3,4,5};
f(A,B[2]);
printf(“A[2] = %d, B[2] = %d\n”, A[2], B[2]);
return 0; A[2] = 10, B[2] = 3
}
32
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Example: Square each element of array
#include <stdio.h>
void square (int a[], int b);
void square (int x[], size;)
int main()
{
{
int i;
int a[100], i, n;
for (i=0;i<size;i++)
scanf (”%d”, &n);
x[i] = x[i]*x[i];
for (i=0; i<n; i++)
scanf (”%d”, &a[i]);
return;
}
square (a, n);
33
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Header files and preprocessor
34
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Header Files
Header files:
• Contain function declarations / prototypes for library functions.
• <stdlib.h> , <math.h> , etc.
• Load with: #include <filename>
• Example: #include <math.h>
• The function definitions of library functions are in the actual libraries (e.g., math library).
35
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
C preprocessor
36
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
#define: Macro definition
Preprocessor directive in the following form:
#define string1 string2
#define PI 3.1415926
int main()
int main()
macro pre-processing
{
{
float r = 4.0, area;
float r = 4.0, area;
area = 3.1415926 * r * r;
area = PI * r * r;
return 0;
return 0;
}
}
37
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
#define with arguments
#define statement may be used with arguments.
• Example: #define sqr(x) x*x
• How will macro substitution be carried out?
r = sqr(a) + sqr(30); 🡪 r = a*a + 30*30;
r = sqr(a+b); 🡪 r = a+b*a+b;
Macros are not functions. They are literally substituted without evaluation.
38
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
Practice Problems
No separate problems needed.
• Look at everything that you did so far, such as finding sum, finding average, counting something, checking if
something is true or false (“ Is there an element in array A such that….) etc. in which the final answer is one
thing only (like sum, count, 0 or 1,…).
• Then for each of them, rather than doing it inside main (as you have done so far), write it as a function with
appropriate parameters, and call from main() to find and print.
• Normally, read and print everything from main(). Do not read or print anything inside the function. This will
give you better practice.
• However, you can write simple functions for printing an array.
39
INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR