MODULE 4 : FUNCTIONS
1.Introduction to Functions in C
A function in C is a named block of statements designed to perform a
specific task. Functions divide a large program into smaller parts, making
it easier to develop, debug, maintain, and reuse code.
Why functions are needed?
1. Modularity: A program can be broken into independent logical units.
2. Reusability: The same function can be used multiple times in a
program.
3. Abstraction: A user can call the function without knowing internal
details.
4. Maintainability: Modifying one function does not affect the entire
program.
5. Teamwork: Different programmers can work on different functions.
General Syntax
return_type function_name(parameter_list)
{
// statements
}
Explanation of terms:
a) return_type: Type of value function will return. Use void if no value
is returned.
b) function_name: Must be a valid C identifier.
c) parameter_list: List of input variables (optional).
d) Function body: Contains actual code that performs required operation.
Example
int add(int a, int b)
{
return a + b;
}
Explanation:
The function takes two integers and returns their sum. The variables a and
b are local to the function.
2.Function Scope: Local Variables
Variables declared inside a function or block (like inside {}) are local
variables.
Characteristics of Local Variables
1) They exist only during the function’s execution.
2) They are stored in stack memory.
3) They are automatically destroyed once the function ends.
4) They cannot be accessed outside that function or block.
5) They are uninitialized by default (may contain garbage value).
Example
void demo()
{
int x = 10; // local variable
printf("%d", x);
}
Here, x exists only during demo() execution. It cannot be used in any other
function.
3.Function Arguments (Parameters)
Function parameters are treated similarly to local variables inside the
function. They receive values when the function is called.
Example
int is_in(char *s, char c)
{
while (*s)
if (*s == c)
return 1;
else
s++;
return 0;
}
Explanation:
a. The function checks if character c exists in string s.
b. s is a pointer to the string.
c. *s gives the current character.
d. If match found → returns 1; otherwise returns 0.
4.Call by Value
C uses call-by-value by default.
How it works
1. A copy of the actual argument is passed.
2. Modifying the parameter inside function does not change the actual
variable.
Example
int sqr(int x)
{
x = x * x;
return x;
}
Calling:
int t = 10;
printf("%d ",
sqr(t));
printf("%d", t);
Output
100 10
Explanation:
t remains 10 because only its copy was modified.
5.Call by Reference (Using Pointers)
Call-by-reference allows modifying actual variables by passing their
addresses.
How it works
1) The address of a variable is passed using &.
2) Function receives pointer parameters.
3) Using *, the function dereferences pointer and modifies actual value.
Example: swap() function
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
Calling:
swap(&a, &b);
Here, a and b are actually modified.
6.Passing Arrays to Functions
Arrays behave differently from basic variables.
When an array is passed to a function:
1. The array decays into a pointer.
2. The function receives the address of the first element.
3. Hence, modifications inside the function affect the original array.
Example
void modify(int arr[])
{
arr[0] = 100;
}
Calling:
int a[5] = {1,2,3,4,5};
modify(a);
Now a[0] becomes 100.
7.Command Line Arguments (argc, argv)
C allows users to pass inputs directly from the terminal.
Function header
int main(int argc, char *argv[])
Explanation
i. argc: Argument count (number of items provided on command line)
ii. argv: Argument vector (array of strings)
The first argument argv[0] is the program name by convention.
Example
printf("%s", argv[1]);
If executed as:
program John
Output:
John
8.The return Statement
The return statement is used to:
1. Return value to the caller
2. Terminate function execution
immediately Example
return x * x;
If return type is void, using return; simply exits the function.
9.Recursion
Recursion occurs when a function calls itself.
Used for problems that can be divided into smaller subproblems.
Features
1) A base condition must be present to stop infinite recursion.
2) Uses stack memory extensively.
3) Elegant but may be slower than loops for large input.
Example: Factorial
int fact(int n)
{
if(n == 1)
return 1; // base case
return n * fact(n-1); // recursive call
}
10.Function Prototypes
Function prototypes inform the compiler about:
1. Function name
2. Return type
3. Parameters and their types
They avoid errors by ensuring type checking.
Syntax
return_type function_name(type1, type2);
Example
int add(int, int);
Function definitions can appear after main() if prototypes are declared
before.
11.The inline Keyword (C99)
The inline keyword suggests the compiler to replace the function call with
the actual code.
Purpose
1) Reduce function call overhead
2) Improve performance
3) Works best for small, frequently-used
functions Important Note
a) Compiler may ignore inline
b) Used only as an optimization
hint Example
inline int add(int a, int b)
{
return a + b;
}
12.Pointers to Functions
In C, a function’s address can be stored in a pointer.
Useful for:
1. Callback functions
2. Event-driven programming
3. Menu-driven systems
4. Passing functions as
parameters Syntax
return_type (*ptr)(parameter_list);
Example
int (*p)(const char*, const char*);
p = strcmp;
Calling
p(a, b);
13.Function Pointer Full Example
void check(char *a, char *b, int (*cmp)(const char *, const char *))
{
if(!(*cmp)(a, b))
printf("Equal");
else
printf("Not Equal");
}
A callback mechanism is demonstrated here.
14.Dynamic Memory Allocation
Dynamic memory is allocated during runtime using library functions.
Functions
1) malloc()
2) calloc()
3) realloc()
4) free()
malloc()
Syntax
pointer = malloc(size_in_bytes);
Example
char *p = malloc(100);
Must check for NULL
if(p == NULL)
{
printf("Memory not allocated");
exit(1);
}
free()
Used to release dynamically allocated memory.
Syntax:
free(p);
Failing to free memory causes memory leaks.
15. Dynamic Array
Example s = malloc(80);
gets(s);
for(int t = strlen(s)-1; t >= 0; t--)
putchar(s[t]);
free(s);
Explanation:
a. Allocates space for string
b. Prints string in reverse
c. Frees memory
16. Dynamically Allocated 2D
Array Example
int (*p)[10];
p = malloc(40 * sizeof(int));
This declares p as a pointer to an array of 10 integers.
17.restrict Keyword (C99)
The restrict keyword tells the compiler that the pointer is the only
reference to that memory location.
Why it is used?
1. Helps compiler optimize code
2. Avoids aliasing issues
3. Improves performance in
loops Syntax:
int * restrict p;
18.Common Pointer Problems
Mistakes often made by beginners:
1. Uninitialized
pointers int *p;
*p = 10; // Error – p is not pointing anywhere
2.Assigning value instead of address
3.Pointer arithmetic errors
Such as going out of array bounds.
4.Not resetting pointers inside loops
5. Dangling pointers
Using memory after free().
Pointers are powerful but must be used carefully.
19.Storage Class Specifiers
C supports four storage class specifiers:
1) extern
2) static
3) register
4) auto
These define a variable’s:
a. Lifetime
b. Visibility
c. Scope
d. Storage
location extern
Used to declare a variable that is defined elsewhere (another file or below
in same file).
Example
extern int x;
Allows multi-file programming.
static Local Variable
Retains its value across multiple calls.
Example
int series()
{
static int s;
s = s + 23;
return s;
}
Behavior:
1) Initialized only once
2) Value preserved between
calls static Global Variable
Visible only within the file where it is declared.
Prevents unwanted access from other files.
register Specifier
Requests the compiler to store variable in CPU register for fast access.
Example
register int i;
Cannot apply & operator
Compiler may ignore request
auto Specifier
Default for local variables.
Example
auto int x = 10;
Rarely written explicitly because it is the default.