100% found this document useful (1 vote)
7 views48 pages

C Programming 1st Year VTU Notes Module 4

This document covers Module 4 of a Programming in C course, focusing on functions, function pointers, and dynamic memory allocation. It explains the general form of functions, the use of function pointers for flexibility in code, and how to dynamically allocate memory for arrays. Additionally, it discusses the scope of functions and local variables, including static local variables and their behavior in function calls.

Uploaded by

Rohan sn2020
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
7 views48 pages

C Programming 1st Year VTU Notes Module 4

This document covers Module 4 of a Programming in C course, focusing on functions, function pointers, and dynamic memory allocation. It explains the general form of functions, the use of function pointers for flexibility in code, and how to dynamically allocate memory for arrays. Additionally, it discusses the scope of functions and local variables, including static local variables and their behavior in function calls.

Uploaded by

Rohan sn2020
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

@azdocuments

PROGRAMMING IN C
SUBJECT CODE: 1BEIT105/205

MODULE-4

Name:

USN:

College:

AZ Documents
Your Engineering Study Partner
[Link]
PROGRAMMING IN C MODULE-04 AZ Documents

PROGRAMMING IN C
1BEIT105/205
MODULE-04
Functions: The General Form of a Function, Understanding the Scope of a Function,
Function Arguments, argc and argv—Arguments to main(), The return Statement, What
Does main() Return?, Recursion, Function Prototypes, Declaring Variable Length
Parameter Declarations, The inline Keyword.
Pointers (Contd…): Pointers to Functions, C's Dynamic Allocation Functions.
Textbook 1: Chapter 5, Chapter 6
Pointers (Contd…): Pointers to Functions, C's Dynamic Allocation Functions.

POINTERS TO FUNCTIONS IN C
A function pointer is a pointer that stores the address of a function.

Just like variables, functions also have memory addresses in a program.

This address represents the entry point of the function, which is the location where the function begins
execution.

Thus:

Variable pointer → stores address of variable


Function pointer → stores address of function

Function pointers allow:

• Calling functions through pointers

• Passing functions as arguments


• Creating arrays of functions

• Writing flexible and reusable code

Obtaining the Address of a Function

The address of a function can be obtained using the function name without parentheses.

Example:

p = strcmp;

Here:

[Link] 1
PROGRAMMING IN C MODULE-04 AZ Documents

strcmp → address of the strcmp function


This address is stored in the function pointer p.

This is similar to arrays:

array name → address of first element


function name → address of function

Declaration of Function Pointer

General Syntax

return_type (*pointer_name)(parameter_list);

Explanation:

• return_type → return type of function


• pointer_name → name of pointer

• parameter_list → parameters of the function

Example

int (*p)(const char *, const char *);

This means:

p is a pointer to a function that


takes two const char* arguments
and returns an integer

Parentheses around *p are necessary.

Without parentheses, the declaration becomes incorrect.

Example Program

#include <stdio.h>
#include <string.h>

void check(char *a, char *b,


int (*cmp)(const char *, const char *));

int main()
{
char s1[80], s2[80];

[Link] 2
PROGRAMMING IN C MODULE-04 AZ Documents

int (*p)(const char *, const char *);

p = strcmp;

printf("Enter two strings:\n");

gets(s1);
gets(s2);

check(s1, s2, p);

return 0;
}

void check(char *a, char *b,


int (*cmp)(const char *, const char *))
{
printf("Testing for equality\n");

if(!(*cmp)(a,b))
printf("Equal");
else
printf("Not Equal");
}

Program Explanation

Step 1: Function Pointer Declaration

int (*p)(const char *, const char *);


This means:

p → pointer to a function
function returns → int
function parameters → two const char*

Step 2: Assign Function Address

p = strcmp;

Here:

p → address of strcmp function

[Link] 3
PROGRAMMING IN C MODULE-04 AZ Documents

Step 3: Passing Function Pointer


check(s1, s2, p);

The pointer p is passed as an argument.

Step 4: Calling Function Through Pointer

Inside check():

(*cmp)(a,b)

This calls the function pointed to by cmp.


Equivalent syntax:

cmp(a,b);

Both are correct.

However, the first form clearly indicates that a function pointer is being used.

Passing Functions as Arguments

Function pointers allow functions to be passed as parameters to other functions.

Example:
check(s1, s2, strcmp);

This directly passes the address of strcmp.

Thus:

check function → receives comparison function

This technique makes programs more flexible.

Expanded Example
The program can compare either:

• Strings

• Numeric values

depending on the function passed.

Program

[Link] 4
PROGRAMMING IN C MODULE-04 AZ Documents

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

void check(char *a, char *b,


int (*cmp)(const char *, const char *));

int compvalues(const char *a, const char *b);


int main()
{
char s1[80], s2[80];
printf("Enter two values or two strings\n");
gets(s1);
gets(s2);

if(isdigit(*s1))
{
printf("Testing values for equality\n");
check(s1, s2, compvalues);
}
else
{
printf("Testing strings for equality\n");
check(s1, s2, strcmp);
}

return 0;
}
void check(char *a, char *b,
int (*cmp)(const char *, const char *))
{
if(!(*cmp)(a,b))
printf("Equal\n");
else
printf("Not Equal\n");
}
int compvalues(const char *a, const char *b)
{
if(atoi(a) == atoi(b))
return 0;
else

[Link] 5
PROGRAMMING IN C MODULE-04 AZ Documents

return 1;
}

Explanation of Expanded Program

If input begins with a digit:

check(s1, s2, compvalues);

The function compvalues() is used.

compvalues() converts strings to numbers using atoi() and compares them.

Example:

"0123"
"123"

Both become:

123
Thus they are equal numerically.

If input is not numeric:

check(s1, s2, strcmp);

Then normal string comparison is used.

Why Function Pointers Are Useful

Function pointers are used in:


1. Interpreters and Compilers

Instead of writing large switch statements, a program can use an array of function pointers.

2. Callback Functions

A function can call another function passed as an argument.

3. Menu Systems

Example:

[Link] 6
PROGRAMMING IN C MODULE-04 AZ Documents

option 1 → function1
option 2 → function2
option 3 → function3

These functions can be stored in a function pointer array.

4. Mathematical Libraries
Functions like:

sin
cos
tan
log

can be called dynamically using function pointers.

Example of Function Pointer Array

void (*func[3])();
func[0] = add;
func[1] = subtract;
func[2] = multiply;

Then functions can be called as:

func[1]();
Key Points to Remember

1. Functions have addresses in memory.

2. A function pointer stores the address of a function.

3. The function name without parentheses gives its address.

4. Function pointers allow functions to be passed as arguments.

5. Parentheses in pointer declaration are necessary.

Example:

int (*p)(int,int);

[Link] 7
PROGRAMMING IN C MODULE-04 AZ Documents

DYNAMICALLY ALLOCATED ARRAYS IN C


In C programming, arrays are usually declared statically like this:

int arr[50];

Here, memory is allocated at compile time.

However, sometimes we do not know the size of the array until runtime.
In such situations, we use dynamic memory allocation.

Dynamic memory allocation is done using the function:

malloc()

which allocates memory from the heap memory area.

What is a Dynamically Allocated Array?


A dynamically allocated array is an array whose memory is allocated during program execution
using functions like:
• malloc()

• calloc()

• realloc()

Since pointers can be indexed like arrays, dynamically allocated memory can be used exactly like a
normal array.

Example concept:

pointer → dynamically allocated memory → used as array

Syntax for Dynamic Allocation

General syntax:
pointer = malloc(number_of_bytes);

Example:

char *s;
s = malloc(80);

This allocates 80 bytes of memory.

After allocation:

s → points to first byte of allocated memory

[Link] 8
PROGRAMMING IN C MODULE-04 AZ Documents

Example Program (Dynamic String Allocation)


This program:

1. Allocates memory dynamically

2. Accepts a string

3. Prints the string in reverse

Program

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *s;
int t;
s = malloc(80);

if(!s)
{
printf("Memory request failed\n");
exit(1);
}
gets(s);
for(t = strlen(s)-1; t >= 0; t--)
putchar(s[t]);
free(s);
return 0;
}

Explanation of Program

Step 1: Pointer Declaration

char *s;
s is a pointer to character.

Step 2: Dynamic Memory Allocation

s = malloc(80);
This allocates 80 bytes of memory.

Memory structure:

[Link] 9
PROGRAMMING IN C MODULE-04 AZ Documents

s → [ allocated memory block ]

Step 3: Check Allocation

if(!s)

If malloc() fails, it returns NULL.

Therefore we check before using the pointer.

Example failure handling:

printf("Memory request failed");


exit(1);

Step 4: Input String


gets(s);

The pointer s acts like a character array.

Step 5: Reverse Printing

for(t=strlen(s)-1; t>=0; t--)


putchar(s[t]);

Here:

s[t] → array indexing using pointer

Step 6: Free Memory

free(s);

This releases the allocated memory back to the system.

This prevents memory leaks.

Dynamic Multidimensional Arrays

It is also possible to dynamically allocate multidimensional arrays.

However, we must declare a pointer that specifies all dimensions except the first.

[Link] 10
PROGRAMMING IN C MODULE-04 AZ Documents

Example: Dynamic 2-D Array


This program creates a table showing numbers 1 to 10 raised to powers 1–4.

Program

#include <stdio.h>
#include <stdlib.h>
int pwr(int a, int b);
int main()
{
int (*p)[10];
int i, j;
p = malloc(40 * sizeof(int));
if(!p)
{
printf("Memory request failed\n");
exit(1);
}
for(j=1; j<=10; j++)
for(i=1; i<=4; i++)
p[i-1][j-1] = pwr(j,i);
for(j=1; j<=10; j++)
{
for(i=1; i<=4; i++)
printf("%10d ", p[i-1][j-1]);
printf("\n");
}
free(p);
return 0;
}
int pwr(int a, int b)
{
int t=1;
for(; b; b--)
t = t * a;
return t;
}

Pointer Declaration for 2-D Array

The pointer is declared as:

int (*p)[10];

[Link] 11
PROGRAMMING IN C MODULE-04 AZ Documents

Meaning:
p → pointer to array of 10 integers

Parentheses are necessary.

Without them:

int *p[10]

would mean:

array of 10 pointers

which is completely different.

Memory Allocation

p = malloc(40 * sizeof(int));

This allocates memory for 40 integers.


Because:

4 rows × 10 columns = 40 integers

Accessing Elements
Even though memory was dynamically allocated, elements are accessed normally:

p[i][j]

Thus the pointer behaves exactly like a 2-D array.

Pointer Movement

Since:

p → pointer to array of 10 integers


When incremented:

p++

the pointer moves 10 integers forward.

Thus each increment moves to the next row.

[Link] 12
PROGRAMMING IN C MODULE-04 AZ Documents

C++ Compatibility
In C++ the pointer returned by malloc() must be explicitly cast.

Example:

p = (int (*)[10]) malloc(40 * sizeof(int));

Many C programmers also use casting to make programs compatible with both C and C++.

Advantages of Dynamic Arrays

Dynamic arrays provide:


1. Flexible memory allocation

2. Memory allocated only when required

3. Efficient memory usage

4. Ability to create large data structures

FUNCTIONS IN C

Functions are the basic building blocks of a C program.


All program activities occur inside functions.

A function is a self-contained block of code that performs a specific task.

Benefits of using functions:


• Improves program readability

• Enables code reuse


• Reduces program complexity

• Makes programs easier to debug and maintain

Example tasks performed by functions:

• Calculating values

• Processing data
• Handling input/output

• Performing mathematical operations

[Link] 13
PROGRAMMING IN C MODULE-04 AZ Documents

General Form of a Function


The general syntax of a function in C is:

return_type function_name(parameter_list)
{
body of the function
}

Explanation of Components
1. Return Type (ret-type)

The return type specifies the type of value returned by the function.

Examples:

int
float
char
double
void

Example:

int sum()
This function returns an integer value.

Important rule:

A function can return any data type except an array.

2. Function Name

The function name identifies the function.

Example:
sum
display
calculate
check

Rules for function names are the same as variable naming rules.

3. Parameter List

[Link] 14
PROGRAMMING IN C MODULE-04 AZ Documents

The parameter list contains variables that receive values from the function call.
Syntax:

type parameter_name

Example:

int add(int a, int b)

Here:

a and b are parameters

Parameters receive values called arguments.

4. Function Body

The function body contains the actual instructions executed when the function is called.

Example:
{
int c;
c = a + b;
return c;
}

Example of a Simple Function

#include <stdio.h>
int add(int a, int b)
{
int result;
result = a + b;
return result;
}
int main()
{
int x = 5;
int y = 10;
int sum;
sum = add(x, y);
printf("Sum = %d", sum);
return 0;
}

[Link] 15
PROGRAMMING IN C MODULE-04 AZ Documents

Output
Sum = 15

Explanation:

1. main() calls add()

2. Values x and y are passed as arguments

3. Function calculates the sum

4. Result is returned to main()

Functions Without Parameters

A function may not require parameters.

Example:

void display(void)
{
printf("Hello World");
}

Here:
void → indicates no parameters

Function Parameter Declaration Rules

Unlike variables, each parameter must include its own type declaration.

Correct declaration:

f(int i, int k, int j)

Incorrect declaration:
f(int i, k, float j)

Reason:

k does not have a type specified

Correct version:

f(int i, int k, float j)

[Link] 16
PROGRAMMING IN C MODULE-04 AZ Documents

Scope of Functions
Scope refers to the region of a program where a variable or function is accessible.

In C, each function creates its own block scope.

Function Scope Rules

Each function is a separate block of code.

This means:

• Code inside one function cannot directly access another function's variables.
• Interaction between functions occurs only through function calls.

Example:

Function A cannot directly access variables of Function B.

Local Variables

Variables declared inside a function are called local variables.

Example:

void func()
{
int x = 10;
}

Here:

x is a local variable

Properties of local variables:

• Created when the function starts execution


• Destroyed when the function ends

• Accessible only inside that function

Lifetime of Local Variables

Local variables:

exist only during function execution

Example:

[Link] 17
PROGRAMMING IN C MODULE-04 AZ Documents

Function called → variable created


Function returns → variable destroyed

Thus:
Local variables cannot retain values between function calls

Static Local Variables

To retain values between function calls, variables can be declared as static.

Example:

void counter()
{
static int count = 0;
count++;
printf("%d", count);
}
Here:

count retains its value between calls


Although it behaves like a global variable in storage, its scope remains limited to the function.

Function Parameters Scope

Parameters also have local scope.

Example:

int add(int a, int b)

Here:
a and b exist only inside add()

When the function ends:

parameters are destroyed

[Link] 18
PROGRAMMING IN C MODULE-04 AZ Documents

Function Scope vs Global Scope

Type Scope Lifetime

Inside function During function


Local variable
only execution

Inside function
Static variable Entire program
only

Global variable Entire program Entire program

Functions Cannot Be Nested


In C:

Functions cannot be defined inside other functions

Example (Invalid):
int main()
{
int add()
{
return 5;
}
}

This is not allowed in C.

Thus:

All functions must be defined at file level.


This is why C is not a block-structured language.

FUNCTION ARGUMENTS IN C

Functions in C often need to receive data from the calling function in order to perform their tasks.
This data is passed through arguments.
The variables that receive these arguments inside the function are called parameters.

Thus:

Arguments → values passed during function call


Parameters → variables that receive those values

Example:

[Link] 19
PROGRAMMING IN C MODULE-04 AZ Documents

int add(int a, int b)


Here:

• a and b are parameters

• The values passed during the function call are arguments

Function Parameters

When a function accepts arguments, it must declare parameters in the function header.

Example
int is_in(char *s, char c)
{
while(*s)
if(*s == c)
return 1;
else
s++;
return 0;
}

Explanation

This function checks whether a character exists in a string.

Parameters:
char *s → pointer to string
char c → character to search

Operation:
1. The function scans the string character by character.

2. If the character c is found, it returns 1.

3. If the end of the string is reached without finding it, it returns 0.

Behavior of Parameters

Function parameters behave just like local variables.

Characteristics:
• They exist only inside the function

• They are created when the function is called

[Link] 20
PROGRAMMING IN C MODULE-04 AZ Documents

• They are destroyed when the function finishes execution


Example:

int square(int x)
{
x = x * x;
return x;
}

Here:

x is a parameter

It behaves like a local variable within the function.

Methods of Passing Arguments

In programming languages, arguments can be passed in two ways:

1. Call by Value

2. Call by Reference

Call by Value

Call by value means that the value of the argument is copied into the parameter.
Thus:

Argument value → copied into parameter

Any changes made inside the function do not affect the original variable.

Example of Call by Value

#include <stdio.h>
int sqr(int x);
int main()
{
int t = 10;
printf("%d %d", sqr(t), t);
return 0;
}
int sqr(int x)
{
x = x * x;

[Link] 21
PROGRAMMING IN C MODULE-04 AZ Documents

return x;
}

Output
100 10

Explanation

1. t = 10

2. t is passed to sqr()

3. Inside sqr(), parameter x receives a copy of 10

4. x becomes 100

5. But the original variable t remains 10

Thus:
Function cannot modify original variable

Call by Reference

Call by reference means that the address of the argument is passed instead of the value.

Thus:

Address of variable → passed to function

The function can modify the original variable.


In C, call by reference is implemented using pointers.

Creating Call by Reference in C

To create call by reference:

1. Pass the address of the variable

2. Receive it using pointer parameters

Example syntax:
function(&variable);

Example: Swapping Two Numbers

#include <stdio.h>

[Link] 22
PROGRAMMING IN C MODULE-04 AZ Documents

void swap(int *x, int *y);


int main()
{
int i = 10;
int j = 20;
printf("Before swapping: %d %d\n", i, j);
swap(&i, &j);
printf("After swapping: %d %d\n", i, j);
return 0;
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}

Output
Before swapping: 10 20
After swapping: 20 10
Explanation

1. The addresses of i and j are passed

2. Pointer parameters receive these addresses

3. Using *x and *y, the original values are modified

4. Thus the values are successfully swapped

Passing Arrays to Functions

Passing arrays to functions is a special case.


Normally C uses call by value, but when arrays are passed:

the address of the array is passed

Thus the function operates on the original array.

Example

void print_upper(char *string)


{

[Link] 23
PROGRAMMING IN C MODULE-04 AZ Documents

int t;

for(t = 0; string[t]; t++)


{
string[t] = toupper(string[t]);
putchar(string[t]);
}
}

Explanation

Here:

string → pointer to array


The function converts each character to uppercase.

Since the original array is modified, the changes remain after the function returns.

Example Program

#include <stdio.h>
#include <ctype.h>
void print_upper(char *string);
int main()
{
char s[80];
printf("Enter a string: ");
gets(s);
print_upper(s);
printf("\nString now: %s", s);
return 0;
}
void print_upper(char *string)
{
int t;
for(t = 0; string[t]; t++)
{
string[t] = toupper(string[t]);
putchar(string[t]);
}
}

Output

[Link] 24
PROGRAMMING IN C MODULE-04 AZ Documents

Enter a string: This is a test


THIS IS A TEST
String now: THIS IS A TEST

The original string s is modified.

Avoiding Modification of Arrays


If we do not want to modify the array, we can simply avoid changing the elements.

Example:

void print_upper(char *string)


{
int t;

for(t = 0; string[t]; t++)


putchar(toupper(string[t]));
}

Now the original string remains unchanged.

Command Line Arguments

Sometimes information is passed to a program from the command line.

Example command:
program_name argument1 argument2

These arguments are received using:

argc
argv

argc

argc → argument count

It stores the number of command line arguments.

Note:

argc is always at least 1


because the program name itself is counted.

[Link] 25
PROGRAMMING IN C MODULE-04 AZ Documents

argv
argv → argument vector

It is an array of character pointers.

Each element points to one argument.

Example:

argv[0] → program name


argv[1] → first argument
argv[2] → second argument

Example Program

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if(argc != 2)
{
printf("You forgot to type your name.\n");
exit(1);
}
printf("Hello %s", argv[1]);
return 0;
}

Example Run

program Tom
Output:
Hello Tom

THE RETURN STATEMENT IN C

The return statement is used in functions to terminate the execution of the function and transfer
control back to the calling function.

It is one of the most important statements in C because it enables functions to send results back to the
caller.

The return statement has two main purposes:

1. Terminate the execution of a function

[Link] 26
PROGRAMMING IN C MODULE-04 AZ Documents

2. Return a value to the calling function


General syntax:

return expression;

or

return;

The first form returns a value, while the second simply exits the function.

Returning from a Function


A function can terminate in two ways.

Method 1: Reaching the end of the function

When the last statement of a function executes and the closing brace } is reached, the function
automatically returns control to the calling function.

Example:

#include <stdio.h>
#include <string.h>
void pr_reverse(char *s);
int main()
{
pr_reverse("I like C");
return 0;
}
void pr_reverse(char *s)
{
int t;
for(t = strlen(s)-1; t >= 0; t--)
putchar(s[t]);
}

Explanation
1. The function pr_reverse() prints a string in reverse order.

2. After finishing the loop, execution reaches the closing brace }.

3. At this point, the function automatically returns to main().

However, most functions do not rely on this automatic return and instead use explicit return
statements.

[Link] 27
PROGRAMMING IN C MODULE-04 AZ Documents

Using the return Statement


The return statement explicitly stops function execution and returns control to the caller.

Example:

int find_substr(char *s1, char *s2)


{
int t;
char *p, *p2;
for(t = 0; s1[t]; t++)
{
p = &s1[t];
p2 = s2;
while(*p2 && *p2 == *p)
{
p++;
p2++;
}

if(!*p2)
return t;
}
return -1;
}

Explanation
This function searches for a substring inside another string.

• If the substring is found → return the starting index

• If the substring is not found → return -1

This function contains two return statements:

return t; → substring found


return -1; → substring not found
Using multiple return statements often makes code simpler and more efficient.

Returning Values

All functions except those declared with void return a value.


Example:

int sum(int a, int b)


{

[Link] 28
PROGRAMMING IN C MODULE-04 AZ Documents

return a + b;
}

Here:
a + b → returned value

The returned value can then be used in expressions.

Example:

x = power(y);

or

if(max(a,b) > 100)


printf("greater");

or

for(ch = getchar(); isdigit(ch); )

Thus, functions can behave like operands in expressions.

Rules for Returning Values

Rule 1

The return type must match the function type.

Example:

int func()
{
return 5;
}

Rule 2

A function declared as void cannot return a value.

Example:

void display()
{
printf("Hello");
}

Rule 3

Function calls cannot appear on the left side of an assignment.

Incorrect:

[Link] 29
PROGRAMMING IN C MODULE-04 AZ Documents

swap(x,y) = 100;
Correct usage:

z = swap(x,y);

Behavior in C89 vs C99

In C89

If a non-void function executes:

return;
without a value, a garbage value is returned.

In C99 and C++

A non-void function must return a value.

Otherwise the result is undefined behavior.


Example of bad practice:

int func()
{
}

This may return an unpredictable value.

Types of Functions Based on Return Behavior

Functions generally fall into three categories.


1. Computational Functions

These perform calculations and return results.

Examples:

sqrt()
sin()
cos()
pow()

Example:
int square(int x)
{
return x*x;
}

[Link] 30
PROGRAMMING IN C MODULE-04 AZ Documents

Status Returning Functions


These perform an operation and return a status value indicating success or failure.

Example:

fclose()

Returns:

0 → success
EOF → error

Procedural Functions

These functions perform tasks but do not return values.

Example:
exit()
printf()
These functions are declared with type:

void

Ignoring Return Values

Even if a function returns a value, the program does not have to store it.

Example:

int mul(int a, int b)


{
return a*b;
}

Usage:

z = mul(x,y); → stored in variable


printf("%d", mul(x,y)); → used in expression
mul(x,y); → return value ignored

Thus:

Return values can be used or discarded.

[Link] 31
PROGRAMMING IN C MODULE-04 AZ Documents

Returning Pointers
Functions can also return pointers.

Since pointers store memory addresses, the function must specify the correct pointer type.

Example:

char *match(char c, char *s)


{
while(c != *s && *s)
s++;

return s;
}

Explanation

This function searches for a character in a string.

If found:
return pointer to matching character

If not found:
return pointer to null terminator

Example program:

char s[80], *p, ch;


gets(s);
ch = getchar();
p = match(ch, s);
if(*p)
printf("%s", p);
else
printf("No match found");

Generic Pointer Return

Sometimes a function must return a pointer of unknown type.

In such cases the return type is:

void *

Example:

malloc()

[Link] 32
PROGRAMMING IN C MODULE-04 AZ Documents

returns:
void *

Functions of Type void

Functions declared with void do not return any value.

Example:

void print_vertical(char *str)


{
while(*str)
printf("%c\n", *str++);
}
Example program:

int main(int argc, char *argv[])


{
if(argc > 1)
print_vertical(argv[1]);

return 0;
}

Output example for input HELLO:

H
E
L
L
O

Return Value of main()

The main() function returns an integer value to the operating system.


Example:

int main()
{
return 0;
}

Meaning:

0 → successful program execution

[Link] 33
PROGRAMMING IN C MODULE-04 AZ Documents

Returning a value from main() is equivalent to calling:


exit(0);

If main() does not explicitly return a value:

result is technically undefined

Although many compilers automatically return 0.

RECURSION IN C

In C programming, a function can call itself during its execution.


This technique is called recursion, and such a function is called a recursive function.

Recursion is the process of defining a problem in terms of itself.

In simple terms:
A recursive function is a function that calls itself.

Recursive functions are widely used for solving problems that can be broken down into smaller
subproblems of the same type.

Structure of a Recursive Function

Every recursive function must contain two essential parts:

1. Base Condition (Stopping Condition)

The condition that stops recursion.

Without this condition, the function will call itself infinitely, causing a stack overflow.
2. Recursive Call

The function calls itself with a modified argument.

Example: Factorial Using Recursion

The factorial of a number n is defined as:

n! = n × (n-1) × (n-2) × ... × 1

Example:

3! = 3 × 2 × 1 = 6
Recursive Definition

n! = n × (n-1)!

[Link] 34
PROGRAMMING IN C MODULE-04 AZ Documents

Recursive Program
int factr(int n)
{
int answer;
if(n == 1)
return 1;
answer = factr(n-1) * n;
return answer;
}

Iterative Version of Factorial


int fact(int n)
{
int t, answer;
answer = 1;
for(t = 1; t <= n; t++)
answer = answer * t;
return answer;
}

Working of Recursive Function

Example:

factr(3)

Execution sequence:

factr(3)
= 3 × factr(2)
factr(2)
= 2 × factr(1)
factr(1)
=1

Now returning values:

factr(2) = 2 × 1 = 2
factr(3) = 3 × 2 = 6

Final result:

3! = 6

[Link] 35
PROGRAMMING IN C MODULE-04 AZ Documents

Recursion and Stack Memory


Each recursive function call creates a new set of local variables and parameters.

These are stored in a memory area called the stack.

When recursion occurs:

1. Each function call creates a new stack frame

2. Local variables are stored in the stack

3. When the function returns, the stack frame is removed

Thus recursive functions expand and contract like a telescope.


Example stack sequence:

factr(3)
factr(2)
factr(1)

Then returning:
factr(1) returns
factr(2) returns
factr(3) returns

Stack Overflow
Since every recursive call uses stack memory, excessive recursion can exhaust the stack.

This causes a stack overflow, which usually crashes the program.

Example problem:
missing base condition

Example error:

int f(int n)
{
return f(n-1);
}

This function will run forever.

Advantages of Recursion

1. Makes complex algorithms simpler

[Link] 36
PROGRAMMING IN C MODULE-04 AZ Documents

2. Improves readability of code


3. Useful for problems with self-similar structure

4. Used in advanced algorithms

Examples:

• Quick Sort

• Tree Traversal

• Artificial Intelligence search algorithms

Disadvantages of Recursion

1. Uses more memory (stack space)

2. Slower due to repeated function calls

3. Risk of stack overflow


4. Harder to debug in some cases

Thus iterative solutions are sometimes more efficient.

FUNCTION PROTOTYPES IN C
In modern C programming, functions must be declared before they are used.

This is usually done using a function prototype.

A function prototype informs the compiler about:

• Function name

• Return type

• Parameter types

• Number of parameters
This allows the compiler to perform strong type checking.

Function prototypes were introduced in C89.

General Form of Function Prototype

return_type function_name(parameter_types);

Example:

[Link] 37
PROGRAMMING IN C MODULE-04 AZ Documents

int sum(int a, int b);


Here:

int → return type


sum → function name
int a, int b → parameters

Example of Function Prototype

#include <stdio.h>

void sqr_it(int *i); // function prototype

int main()
{
int x;

x = 10;

sqr_it(x); // error: type mismatch

return 0;
}

void sqr_it(int *i)


{
*i = *i * *i;
}

Explanation

The prototype requires:


int *

But the call passes:

int

Thus the compiler detects a type mismatch error.

This prevents serious bugs.

Importance of Function Prototypes


Function prototypes provide:

[Link] 38
PROGRAMMING IN C MODULE-04 AZ Documents

1. Type Checking
Ensures arguments match parameter types.

2. Error Detection

Detects incorrect function calls.

3. Correct Code Generation

Compiler knows parameter types before compilation.

4. Improved Program Safety

Prevents invalid conversions.

Function Definition as Prototype

If a function definition appears before its use, it can act as its own prototype.

Example:
#include <stdio.h>
void f(int a, int b)
{
printf("%d", a % b);
}
int main()
{
f(10,3);

return 0;
}
Since f() is defined before main(), no prototype is needed.

Prototype for Functions with No Parameters


In C, a function with no parameters is declared as:

float f(void);

This explicitly tells the compiler that the function takes no parameters.

In C++, the following is enough:

int f();

But in C this means parameter information is not specified.

[Link] 39
PROGRAMMING IN C MODULE-04 AZ Documents

Old-Style Function Declarations


Early versions of C used old-style declarations.

Example:

double div();

This only tells the compiler the return type, not the parameter types.

Example program:

#include <stdio.h>
double div();
int main()
{
printf("%f", div(10.2,20.0));
}
double div(double num, double denom)
{
return num/denom;
}
This approach is now obsolete.

Standard Library Function Prototypes

All standard library functions must be declared using header files.

Example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

Header files contain:

• Function prototypes

• Macro definitions

• Library constants
Example:

stdio.h → printf(), scanf()


stdlib.h → malloc(), exit()
string.h → strlen(), strcpy()

[Link] 40
PROGRAMMING IN C MODULE-04 AZ Documents

Variable Length Parameter Lists


Some functions accept variable numbers of arguments.

Example:

printf()

Prototype example:

int func(int a, int b, ...);

The ... indicates additional arguments may follow.

Rules:
• At least one parameter must exist

• ... must appear at the end

Incorrect:

int func(...); // illegal

Implicit int Rule (Obsolete)

Older C versions assumed int when no type was specified.

Example:
f() { return 0; }

Here:

return type defaults to int

This rule is removed in C99 and C++.

Modern code must always explicitly declare types.

Old-Style Parameter Declaration


Earlier C versions used a different parameter declaration format.

Modern form:

float f(int a, int b, char ch)


{
}
Old form:

[Link] 41
PROGRAMMING IN C MODULE-04 AZ Documents

float f(a,b,ch)
int a,b;
char ch;
{
}

This style is obsolete and not supported in C++.

THE INLINE KEYWORD IN C

The inline keyword was introduced in the C99 standard of the C programming language. It is used
with functions to suggest to the compiler that the function should be expanded inline instead of
being called normally.

In a normal function call, the program control jumps to the function, executes the function code, and
then returns to the calling point. This process involves function call overhead such as:

• Saving registers

• Passing parameters

• Jumping to the function location

• Returning back to the calling function

The inline keyword helps reduce this overhead by requesting the compiler to replace the function call
with the actual function code.

Thus, instead of calling the function repeatedly, the compiler inserts the function body directly at the
point where it is called.

Syntax of Inline Function


The general syntax for declaring an inline function is:

inline return_type function_name(parameters)


{
function body
}

Example:

inline int square(int x)


{
return x * x;
}

When this function is called:

[Link] 42
PROGRAMMING IN C MODULE-04 AZ Documents

y = square(5);
The compiler may replace it internally with:

y = 5 * 5;

Thus avoiding the overhead of a function call.

Working of Inline Functions

Normally, a function call works as follows:

1. Arguments are passed to the function.


2. Control jumps to the function.

3. The function executes its instructions.

4. Control returns to the calling function.

However, when a function is declared as inline, the compiler may expand the function directly into
the calling code.

Example:

inline int add(int a, int b)


{
return a + b;
}
Function call:

sum = add(10, 20);

Possible compiled code:


sum = 10 + 20;

Thus the function body replaces the function call.

Example Program Using Inline Function


#include <stdio.h>
inline int cube(int n)
{
return n*n*n;
}
int main()
{
int x = 3;

[Link] 43
PROGRAMMING IN C MODULE-04 AZ Documents

printf("Cube = %d", cube(x));


return 0;
}

Output

Cube = 27

Here the function cube() may be expanded directly in main().

Inline is Only a Request

It is important to understand that the inline keyword is only a request or suggestion to the compiler.

The compiler may:

• Accept the request and inline the function

• Ignore the request and treat it as a normal function

This decision depends on several factors such as:


• Function size

• Compiler optimization settings

• Complexity of the function

Thus, the programmer cannot force the compiler to inline a function.

Advantages of Inline Functions

1. Reduces Function Call Overhead

Inline functions eliminate the overhead of:


• Stack operations

• Jump instructions

• Parameter passing

2. Improves Execution Speed

Since function calls are removed, execution becomes faster, especially in frequently called functions.

3. Useful for Small Functions

Inline functions are ideal for small, frequently used functions, such as:

• Mathematical operations
• Accessor functions

• Utility functions

[Link] 44
PROGRAMMING IN C MODULE-04 AZ Documents

4. Improves Code Readability


They allow programmers to write reusable functions without sacrificing performance.

Disadvantages of Inline Functions

1. Increased Code Size

Since the function body is copied wherever it is called, it may increase the size of the compiled
program.

2. Not Suitable for Large Functions

Inlining large functions can increase memory usage and reduce efficiency.

3. Compiler May Ignore It

Since inline is only a suggestion, the compiler may not inline the function.

Inline Functions vs Macros

Before the introduction of inline functions, programmers often used macros for similar purposes.

Example macro:

#define SQUARE(x) ((x)*(x))

Example inline function:

inline int square(int x)


{
return x*x;
}
Advantages of Inline Functions over Macros

Inline Function Macro

Type checked No type checking

Debuggable Hard to debug

Safer Prone to errors

Follows function rules Simple text replacement

Thus inline functions are safer than macros.

[Link] 45
PROGRAMMING IN C MODULE-04 AZ Documents

Inline Keyword in C++


The inline specifier is also supported by C++.

In C++:

• Inline functions are commonly used in classes

• They are often used for small member functions

• They help improve performance in object-oriented programs

Example in C++:

inline int multiply(int a, int b)


{
return a*b;
}

[Link] 46
Thank You
We’re glad to be part of your engineering journey.
Keep exploring, keep innovating, and keep growing.

AZ Documents
Your Engineering Study Partner
[Link]

Quality notes, simplified explanations, and


student-focused resources for every semester.

Connect With Us:


[Link] [Click Here]

@azdocuments [Click Here]


Join Our Student Community: [Click Here]

© 2025 AZ Documents. All rights reserved.


This material is intended for educational purposes only.
Redistribution without permission is prohibited.

You might also like