Functions in C
Computing Lab
https://www.isical.ac.in/~dfslab
Indian Statistical Institute
Computing Lab (ISI) Functions 1 / 23
Basics
“Sub”-program
e.g., gcd, area of a triangle
Usually takes 1 or more arguments (input values)
May compute a return value (output)
Syntax
return_type function_name (argument1_type argument1,
argument2_type argument2,
... )
{
/* function body (local variables + statements) */
}
return statement
return; or
return expression;
void: special keyword to denote no arguments or return value
Computing Lab (ISI) Functions 2 / 23
Using functions
Syntax
In an expression:
x = ... * function_name(input1, input2, ...) - ... ;
Only for the effect: function_name(input1, input2, ...);
Ordering, number and types of inputs given to a function call must
match with the ordering, number and types of arguments in the
function header.
Computing Lab (ISI) Functions 3 / 23
How does the computer handle function calls?
1 void main(void)
2 { ...
3 m = f(x, y*z); 1. Let a = x, b = y*z,
4 ... i.e., copy x, y*z into a, b
5 }
6
2. Execute the statements in f().
7 int f(int a, int b) (a) If a is positive, let m = b.
8 { ... Execute the statements in g().
9 if (a > 0)
10 p = g(b); (b) Otherwise, let n = b/2.
11 else Execute the statements in h().
12 p = h(b / 2); (c) In either case, return the value
13 return p; stored in p (obtained from g() or
14 } h()).
15
16 int g(int m) (d) Return the value p to the calling
17 { ... } function (main).
18
19 int h(int n)
3. Continue from line 4.
20 { ... }
Computing Lab (ISI) Functions 4 / 23
Prototypes
Prototype
return_type function_name (type1 argument1, type2 argument2, ... );
Example: static double entropy(int, int);
Used to “announce” functions before they are actually written
Argument types have to be specified, but argument names are
optional
Note the semicolon at the end
Actual function may be written later within the same file,
or in different file ←− LATER
Computing Lab (ISI) Functions 5 / 23
Call by value
A copy is made of any variable that is passed as an input argument to
a function
Changes to the variable inside the function are not visible outside
Exception: arrays / pointers
used whenever a function needs to change an argument
Computing Lab (ISI) Functions 6 / 23
Global, local variables
Global variables: variables defined outside of the body of any function
stored in the data segment
Local variables: variables defined within a function (or block)
not visible (cannot be used) outside the function
hides / masks any global variable with the same name
stored in a region of memory called an activation record or stack frame
Computing Lab (ISI) Functions 7 / 23
Static variables
Defined within a function, but not destroyed when function returns
i.e., retains value across calls to the same function
Example:
void f(void) {
static int i = 1;
printf("This function has executed %d time(s)\n", i);
i++;
}
Computing Lab (ISI) Functions 8 / 23
Arrays / pointers and functions
Computing Lab (ISI) Functions 9 / 23
Review question
For each of the following cases, what is the
1. type of X?
2. value of sizeof(X)?
3. value of sizeof(X[0])?
int *X[10];
int (*X)[10];
NOTE: int X[][10] generates a compiler error
Computing Lab (ISI) Functions 10 / 23
Review question
For each of the following cases, what is the
1. type of X?
2. value of sizeof(X)?
3. value of sizeof(X[0])?
int *X[10]; array of 10 pointers to integers
sizeof(X) : 80 bytes
sizeof(X[0]) : 8 bytes
int (*X)[10];
NOTE: int X[][10] generates a compiler error
Computing Lab (ISI) Functions 10 / 23
Review question
For each of the following cases, what is the
1. type of X?
2. value of sizeof(X)?
3. value of sizeof(X[0])?
int *X[10]; array of 10 pointers to integers
sizeof(X) : 80 bytes
sizeof(X[0]) : 8 bytes
int (*X)[10]; pointer to an array of 10 integers
sizeof(X) : 8 bytes
sizeof(X[0]) : 40 bytes
NOTE: int X[][10] generates a compiler error
Computing Lab (ISI) Functions 10 / 23
One-dimensional array arguments
Equivalent
int f ( int A[100] , int size ) int f ( int A[] , int size )
{ {
... ...
} }
See array-args.c,
https://en.cppreference.com/w/c/language/array
Computing Lab (ISI) Functions 11 / 23
Digression regarding memory / storage
Computing Lab (ISI) Functions 12 / 23
Simplified view of a program’s memory
CPU RAM Hard disk
prog1.c
C code gcc
Code / Text
1000 i
1004
1008
N
a.out
Machine
Global data instructions
malloc, calloc,
free, etc. work Stack (local variables)
with this portion
of memory.
HEAP
Computing Lab (ISI) Functions 13 / 23
Activation records
Where are the activation records (AR) stored?
Simple solution: AR == one fixed block of memory per function
LATER : does not work for recursive functions
Better solution: one block of memory per function call
AR allocated / deallocated when function is called / returns
variables created when function is called; destroyed when function
returns
need to keep track of nested calls
function calls behave in last in first out manner
⇒ use stack to keep track of ARs
Computing Lab (ISI) Functions 14 / 23
Activation stack
Activation records stored in a chunk of memory called activation stack
When a function is called, its activation record is added to the end of
the activation stack.
When function returns, its activation record is removed.
LATER : works for recursive functions
Computing Lab (ISI) Functions 15 / 23
Activation stack: example
1 void main(void)
2 { ...
3 m = f(x, y*z); AR for printf
4 ...
5 }
6
7 int f(int a, int b) AR for h
8 { ...
9 if (a > 0) Stores n
10 p = g(b); AR for f
11 else
12 p = h(b / 2);
13 return p;
14 } Stores a, b, p
15
16 int g(int m) AR for main
17 { ... }
18
Stores m, x, y, z
19 int h(int n)
20 { ... printf(...); ...}
Computing Lab (ISI) Functions 16 / 23
Practice problems I
1. Implement a list of integers using dynamic memory. The list consists
of a header storing two items:
the size of the list, and
a dynamically allocated array capable of storing only the elements in
the list.
Define a structure to store the size of the list, and a dynamically
allocated array that stores the list elements. Use a typedef to define
LIST as the name of your structure.
Implement the following functions.
(a) create_list(void): returns an empty list. For an empty list, the size
is zero, and the array is NULL.
(b) print_list(LIST L): print the elements of the list separated by
spaces, and terminated by a newline.
Computing Lab (ISI) Functions 17 / 23
Practice problems II
(c) append(LIST L, int a): appends a to the end of the list L, and
returns the modified list.
(d) prepend(LIST L, int a): prepends a at the beginning of the list L,
and returns the modified list.
(e) deletelast(LIST L): deletes the last element of the list, and returns
the modified list.
(f) deletefirst(LIST L): deletes the first element of the list, and
returns the modified list.
(g) deleteall(LIST L, int a): deletes all occurrences of a in L, and
returns the modified list.
Do not forget to use free() where necessary.
Computing Lab (ISI) Functions 18 / 23
Practice problems III
Test your code using, for example, the following sequence of
operations.
1 2 3 4
create_list() append(2) prepend(8) deletefirst()
append(9) append(3) prepend(9) deletefirst()
append(1) prepend(9) prepend(1) deletefirst()
append(2) prepend(2) deletelast() deletefirst()
append(3) prepend(4) deletelast() deleteall(7)
append(6) prepend(8) deletelast() deleteall(2)
append(7) prepend(2) deletelast() deleteall(9)
append(8) prepend(5) deletelast() deleteall(4)
append(4) prepend(9) deletefirst() deleteall(7)
SOURCE : IIT Kharagpur, CS19001/CS19002 Programming and Data Structures Laboratory,
2015, Assignment 8.
Computing Lab (ISI) Functions 19 / 23
Practice problems IV
2. Let s and t be strings. Implement the following functions in C:
(a) strlen(s): returns the length of s, i.e., the number of characters
present in s;
(b) strcmp(s, t): returns 1 if s and t are identical, 0 otherwise;
(c) diffByOne(s, t): returns 1 if s and t are of the same length, and
differ in exactly one position, 0 otherwise.
Thus, if s is sale and t is either salt or same or pale, diffByOne(s, t)
should return 1; but if s and t are salt and salty, it should return 0.
3. Write a function uniquify that
takes two arguments: an array A containing non-negative integers, and
n, the number of integers contained in the array, and
stores in A a list of the distinct integers contained in A if the integers in A
are sorted in increasing order, and returns the number of distinct
integers in A; and returns -1 otherwise.
Computing Lab (ISI) Functions 20 / 23
Practice problems V
4. Recall that the rand() function provided by the standard C library
generates a sequence of pseudo-random integers uniformly sampled
from the range [0, RAND_MAX]. For the first part of this question, you
have to use the Box-Muller transform (described below) to generate a
pseudo-random sequence drawn from a normal distribution. [5]
Suppose u1 and u2 are independent samples chosen from the
uniform distribution on the unit interval (0, 1). Let
√
z0 = −2 ln u1 cos(2πu2 )
√
z1 = −2 ln u1 sin(2πu2 )
Then z0 and z1 are independent random variables with a standard
normal distribution.
Computing Lab (ISI) Functions 21 / 23
Practice problems VI
Write a function that uses the above idea to generate a
pseudo-random sequence drawn from a standard normal distribution.
Your function should have the following prototype:
double normal(void);
5. A person’s daily commute from home to office consists of three
stages: she first takes an auto to the nearest Metro station A, then
takes the Metro from station A to station B , and finally takes a bus
from B to her office. Assume that the time taken to complete each
stage follows an independent normal distribution N (µi , σi2 ) for
i = 1, 2, 3. You have to write a program that uses simulation to
estimate the probability that the person’s commute will take more than
a specified amount of time T .
Input format. The values of µ1 , σ1 , µ2 , σ2 , µ3 , σ3 and T (all in
minutes) will be provided in that order via standard input.
Computing Lab (ISI) Functions 22 / 23
Practice problems VII
Output format. Your program should print a single floating point
number corresponding to the desired probability, correct to 8 decimal
places.
Method. You should use the function that you wrote above to
simulate 10,000 journeys, and report the proportion of these journeys
that took more than T minutes.
NOTE : If a random variable X follows the standard normal distribution,
then the random variable Y = aX + b (where a, b are real constants)
follows a normal distribution with mean b and variance a2 .
Computing Lab (ISI) Functions 23 / 23