C Programming 1st Year VTU Notes Module 4
C Programming 1st Year VTU Notes Module 4
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.
This address represents the entry point of the function, which is the location where the function begins
execution.
Thus:
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
General Syntax
return_type (*pointer_name)(parameter_list);
Explanation:
Example
This means:
Example Program
#include <stdio.h>
#include <string.h>
int main()
{
char s1[80], s2[80];
[Link] 2
PROGRAMMING IN C MODULE-04 AZ Documents
p = strcmp;
gets(s1);
gets(s2);
return 0;
}
if(!(*cmp)(a,b))
printf("Equal");
else
printf("Not Equal");
}
Program Explanation
p → pointer to a function
function returns → int
function parameters → two const char*
p = strcmp;
Here:
[Link] 3
PROGRAMMING IN C MODULE-04 AZ Documents
Inside check():
(*cmp)(a,b)
cmp(a,b);
However, the first form clearly indicates that a function pointer is being used.
Example:
check(s1, s2, strcmp);
Thus:
Expanded Example
The program can compare either:
• Strings
• Numeric values
Program
[Link] 4
PROGRAMMING IN C MODULE-04 AZ Documents
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
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;
}
Example:
"0123"
"123"
Both become:
123
Thus they are equal numerically.
Instead of writing large switch statements, a program can use an array of function pointers.
2. Callback Functions
3. Menu Systems
Example:
[Link] 6
PROGRAMMING IN C MODULE-04 AZ Documents
option 1 → function1
option 2 → function2
option 3 → function3
4. Mathematical Libraries
Functions like:
sin
cos
tan
log
void (*func[3])();
func[0] = add;
func[1] = subtract;
func[2] = multiply;
func[1]();
Key Points to Remember
Example:
int (*p)(int,int);
[Link] 7
PROGRAMMING IN C MODULE-04 AZ Documents
int arr[50];
However, sometimes we do not know the size of the array until runtime.
In such situations, we use dynamic memory allocation.
malloc()
• calloc()
• realloc()
Since pointers can be indexed like arrays, dynamically allocated memory can be used exactly like a
normal array.
Example concept:
General syntax:
pointer = malloc(number_of_bytes);
Example:
char *s;
s = malloc(80);
After allocation:
[Link] 8
PROGRAMMING IN C MODULE-04 AZ Documents
2. Accepts a string
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
char *s;
s is a pointer to character.
s = malloc(80);
This allocates 80 bytes of memory.
Memory structure:
[Link] 9
PROGRAMMING IN C MODULE-04 AZ Documents
if(!s)
Here:
free(s);
However, we must declare a pointer that specifies all dimensions except the first.
[Link] 10
PROGRAMMING IN C MODULE-04 AZ Documents
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;
}
int (*p)[10];
[Link] 11
PROGRAMMING IN C MODULE-04 AZ Documents
Meaning:
p → pointer to array of 10 integers
Without them:
int *p[10]
would mean:
array of 10 pointers
Memory Allocation
p = malloc(40 * sizeof(int));
Accessing Elements
Even though memory was dynamically allocated, elements are accessed normally:
p[i][j]
Pointer Movement
Since:
p++
[Link] 12
PROGRAMMING IN C MODULE-04 AZ Documents
C++ Compatibility
In C++ the pointer returned by malloc() must be explicitly cast.
Example:
Many C programmers also use casting to make programs compatible with both C and C++.
FUNCTIONS IN C
• Calculating values
• Processing data
• Handling input/output
[Link] 13
PROGRAMMING IN C MODULE-04 AZ Documents
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:
2. Function Name
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:
Here:
4. Function Body
The function body contains the actual instructions executed when the function is called.
Example:
{
int c;
c = a + b;
return c;
}
#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:
Example:
void display(void)
{
printf("Hello World");
}
Here:
void → indicates no parameters
Unlike variables, each parameter must include its own type declaration.
Correct declaration:
Incorrect declaration:
f(int i, k, float j)
Reason:
Correct version:
[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.
This means:
• Code inside one function cannot directly access another function's variables.
• Interaction between functions occurs only through function calls.
Example:
Local Variables
Example:
void func()
{
int x = 10;
}
Here:
x is a local variable
Local variables:
Example:
[Link] 17
PROGRAMMING IN C MODULE-04 AZ Documents
Thus:
Local variables cannot retain values between function calls
Example:
void counter()
{
static int count = 0;
count++;
printf("%d", count);
}
Here:
Example:
Here:
a and b exist only inside add()
[Link] 18
PROGRAMMING IN C MODULE-04 AZ Documents
Inside function
Static variable Entire program
only
Example (Invalid):
int main()
{
int add()
{
return 5;
}
}
Thus:
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:
Example:
[Link] 19
PROGRAMMING IN C MODULE-04 AZ Documents
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
Parameters:
char *s → pointer to string
char c → character to search
Operation:
1. The function scans the string character by character.
Behavior of Parameters
Characteristics:
• They exist only inside the function
[Link] 20
PROGRAMMING IN C MODULE-04 AZ Documents
int square(int x)
{
x = x * x;
return x;
}
Here:
x is a parameter
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:
Any changes made inside the function do not affect the original variable.
#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()
4. x becomes 100
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:
Example syntax:
function(&variable);
#include <stdio.h>
[Link] 22
PROGRAMMING IN C MODULE-04 AZ Documents
Output
Before swapping: 10 20
After swapping: 20 10
Explanation
Example
[Link] 23
PROGRAMMING IN C MODULE-04 AZ Documents
int t;
Explanation
Here:
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
Example:
Example command:
program_name argument1 argument2
argc
argv
argc
Note:
[Link] 25
PROGRAMMING IN C MODULE-04 AZ Documents
argv
argv → argument vector
Example:
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 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.
[Link] 26
PROGRAMMING IN C MODULE-04 AZ Documents
return expression;
or
return;
The first form returns a value, while the second simply exits 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.
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
Example:
if(!*p2)
return t;
}
return -1;
}
Explanation
This function searches for a substring inside another string.
Returning Values
[Link] 28
PROGRAMMING IN C MODULE-04 AZ Documents
return a + b;
}
Here:
a + b → returned value
Example:
x = power(y);
or
or
Rule 1
Example:
int func()
{
return 5;
}
Rule 2
Example:
void display()
{
printf("Hello");
}
Rule 3
Incorrect:
[Link] 29
PROGRAMMING IN C MODULE-04 AZ Documents
swap(x,y) = 100;
Correct usage:
z = swap(x,y);
In C89
return;
without a value, a garbage value is returned.
int func()
{
}
Examples:
sqrt()
sin()
cos()
pow()
Example:
int square(int x)
{
return x*x;
}
[Link] 30
PROGRAMMING IN C MODULE-04 AZ Documents
Example:
fclose()
Returns:
0 → success
EOF → error
Procedural Functions
Example:
exit()
printf()
These functions are declared with type:
void
Even if a function returns a value, the program does not have to store it.
Example:
Usage:
Thus:
[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:
return s;
}
Explanation
If found:
return pointer to matching character
If not found:
return pointer to null terminator
Example program:
void *
Example:
malloc()
[Link] 32
PROGRAMMING IN C MODULE-04 AZ Documents
returns:
void *
Example:
return 0;
}
H
E
L
L
O
int main()
{
return 0;
}
Meaning:
[Link] 33
PROGRAMMING IN C MODULE-04 AZ Documents
RECURSION IN C
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.
Without this condition, the function will call itself infinitely, causing a stack overflow.
2. Recursive Call
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;
}
Example:
factr(3)
Execution sequence:
factr(3)
= 3 × factr(2)
factr(2)
= 2 × factr(1)
factr(1)
=1
factr(2) = 2 × 1 = 2
factr(3) = 3 × 2 = 6
Final result:
3! = 6
[Link] 35
PROGRAMMING IN C MODULE-04 AZ Documents
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.
Example problem:
missing base condition
Example error:
int f(int n)
{
return f(n-1);
}
Advantages of Recursion
[Link] 36
PROGRAMMING IN C MODULE-04 AZ Documents
Examples:
• Quick Sort
• Tree Traversal
Disadvantages of Recursion
FUNCTION PROTOTYPES IN C
In modern C programming, functions must be declared before they are used.
• Function name
• Return type
• Parameter types
• Number of parameters
This allows the compiler to perform strong type checking.
return_type function_name(parameter_types);
Example:
[Link] 37
PROGRAMMING IN C MODULE-04 AZ Documents
#include <stdio.h>
int main()
{
int x;
x = 10;
return 0;
}
Explanation
int
[Link] 38
PROGRAMMING IN C MODULE-04 AZ Documents
1. Type Checking
Ensures arguments match parameter types.
2. Error Detection
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.
float f(void);
This explicitly tells the compiler that the function takes no parameters.
int f();
[Link] 39
PROGRAMMING IN C MODULE-04 AZ Documents
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.
Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
• Function prototypes
• Macro definitions
• Library constants
Example:
[Link] 40
PROGRAMMING IN C MODULE-04 AZ Documents
Example:
printf()
Prototype example:
Rules:
• At least one parameter must exist
Incorrect:
Example:
f() { return 0; }
Here:
Modern form:
[Link] 41
PROGRAMMING IN C MODULE-04 AZ Documents
float f(a,b,ch)
int a,b;
char ch;
{
}
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
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.
Example:
[Link] 42
PROGRAMMING IN C MODULE-04 AZ Documents
y = square(5);
The compiler may replace it internally with:
y = 5 * 5;
However, when a function is declared as inline, the compiler may expand the function directly into
the calling code.
Example:
[Link] 43
PROGRAMMING IN C MODULE-04 AZ Documents
Output
Cube = 27
It is important to understand that the inline keyword is only a request or suggestion to the compiler.
• Jump instructions
• Parameter passing
Since function calls are removed, execution becomes faster, especially in frequently called 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
Since the function body is copied wherever it is called, it may increase the size of the compiled
program.
Inlining large functions can increase memory usage and reduce efficiency.
Since inline is only a suggestion, the compiler may not inline the function.
Before the introduction of inline functions, programmers often used macros for similar purposes.
Example macro:
[Link] 45
PROGRAMMING IN C MODULE-04 AZ Documents
In C++:
Example in C++:
[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]