0% found this document useful (0 votes)
10 views39 pages

C Functions Overview and Usage Guide

Module 7 - Part 1 focuses on functions in C programming, covering their declaration, definition, and usage. It explains the structure of functions, including the main function, and discusses the concept of call by value. Additionally, the module highlights the advantages and disadvantages of using functions, along with their memory allocation during execution.

Uploaded by

Priyansh Joshi
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
0% found this document useful (0 votes)
10 views39 pages

C Functions Overview and Usage Guide

Module 7 - Part 1 focuses on functions in C programming, covering their declaration, definition, and usage. It explains the structure of functions, including the main function, and discusses the concept of call by value. Additionally, the module highlights the advantages and disadvantages of using functions, along with their memory allocation during execution.

Uploaded by

Priyansh Joshi
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

Module 7 – Part 1 - Functions

BITS Pilani
Pilani Campus
Department of Computer Science & Information Systems
Module Overview

• What are Functions?


• Function Declaration
• Function Definition
• Function Call
• Functions in Memory
• Call by Value
• Exercises

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Functions
Functions
main() function is the
We have already seen functions place where any C
program starts its execution
/* myfirst.c: to compute the sum of two numbers */
#include<stdio.h> //Preprocessor directive
/*Program body*/
int main()
{
int a, b, sum; //variable declarations
printf("Please enter the values of a and b:\n");
scanf("%d %d", &a, &b);
sum = a + b; // the sum is computed
printf("The sum is %d\n", sum);
return 0; //terminates the program
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
What are functions?
• Functions are “Self contained program segment that carries out some
specific well-defined task”
Sum of two numbers:
Two values
int sum(int a, int b) received by the
{ “sum” function
• A function int total;
• processes information that is total = a + b;
return total;
passed to it from the calling
}
portion of the program, and int main() “sum” function computes the sum
of two values and returns it
• returns a single value {
int x,y,z;
x = 5, y = 4;
z = sum(x,y);
• Every C program has one printf(“Sum is %d”,z);
return 0;
or more functions } “main” function calls “sum” function passing
values of x and y and receives their sum.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Types of Functions
• Predefined functions
e.g., scanf(), printf(), getc(), getchar(), exit(), …

• User defined functions

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Using Functions
/* myProg.c */
Functions are #include <stdio.h> Function
Declaration
• Declared int sum(int a, int b);
int sum(int a, int b)
• Defined
{
• Called int total; Function
total = a + b; Definition
return total;
}
int main()
{
int x,y,z;
x = 5, y = 4; Function Call
z = sum(x,y);
printf(“Sum is %d”,z);
return 0;
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Function Declaration
Function Declaration
• Gives information to the compiler that the function may later be used in the
program
• Declarations appear before definitions

• Although optional in many compilers, it is a good practice to use

• Syntax:
<return_type> <function_name> (list-of-typed-parameters);

• Example:
• float sqrt(float x);
• void average(float, float);

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Function Declaration (Contd.)
float average(float a, float b);

Return type of the function Optional list of parameters


• Any valid data type in C • A comma-separated list
• void in case a function of type-name pairs
does not return anything • Or just types
explicitly • It can be an empty list
Name of the function
• Any valid identifier
name Another example

void average(float, float); Note that declarations doesn’t mandate


specifying the variable names

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Function Definition
Function Definition
Syntax:
return_type function_name (list_of_parameters)
{
function body
}

Parts of function definition:


1. Type of the value it returns
2. Name of the function
3. Optional list of typed parameters
4. Function body
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Function Definition
float average(float a, float b) Optional list of parameters
{ • A comma-separated list
float avg; of type-name pairs
• Can’t be just types
avg = (a + b)/2;
Name of the function • Contains formal
return avg; • Any valid identifier parameters
} name • It can be an empty list
Function body
Return type of the function • Lines of C code
• Any valid data type in C evaluating a program
• void in case a function logic Another example
does not return anything
explicitly void print_nums(float a, float b)
{
prinf(“Num1, Num2 are: %f, %f”, a, b);
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matching Function definition
with Function declaration
float average(float x,float y); float average(float a,float b)
{
float avg;
avg = (a + b)/2;
return avg;
}

The following should exactly match between a Function Declaration and a Function
Definition:
• Name of the Function
• Number of Parameters
• Type of each Parameter
• Names of the parameters need not match!
• The return type
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Function Definitions and
Declarations
• Typically, functions are declared first in the program
• Then the functions are defined.
• Although declaring functions is optional, it is recommended to
declare them before defining them otherwise “Warning”
• Helps in writing modular programs
• Typically, functions are declared in “.h” files
• “.h” files are header files
• These “.h” files are included in your “.c” files

We will see more about writing modular programs in lab 8

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Function Call
Calling a function
/* myProg.c */ Function
The functions which #include <stdio.h> Declaration
you have declared int sum(int a, int b);
and (or) defined int sum(int a, int b)
can be called from {
either main() int total; Function
function or any total = a + b; Definition
other function. return total;
}
int main()
Example: Function {
“sum” being called int x,y,z;
Function Call
from “main” x = 5, y = 4;
function z = sum(x,y);
printf(“Sum is %d:”,z};
return 0;
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Calling a function (another
example
#include <stdio.h> int main() {
int sum(int, int); int x,y,z;
int sum_call(int, int); x = 5, y = 4;
int sum(int a, int b) { z = sum_call(x,y);
int total; printf(“Sum is %d:”,z};
total = a + b; return 0;
return total; }
}
int sum_call(int m, int n)
{ • Function “sum” being called
return sum(m,n); from “sum_call” function
} • Function “sum_call” being
called from “main” function
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Calling a Function (Syntax)
function_name (arguments values);

Function Name Argument values


• This should match with • comma-separated list of
the name used in the expressions
function definition and • contains actual parameters
declaration

Examples:
sum(a, b);
sum(a+b, c+d);
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matching Function Call with
Function Definition
int sum(int a, int b); int main(){
int sum(int a, int b){ int x,y,z;
int total; x = 5, y = 4;
total = a + b; z = sum(x,y);
return total; printf(“Sum is %d:”,z};
} return 0;
}
The following should exactly match between a Function Definition and a Function Call:
• The Name of the function
• The number of actual arguments in the function call must match the number of formal
parameters in the function definition
• Type of each argument in the function call must match with the type of the
corresponding parameter in the function definition
– Names of parameters need not match!
• The return type
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Flow of program execution

/* myProg.c */
#include <stdio.h>
int sum(int a, int b);
int sum(int a, int b){
int total;
total = a + b;
return total; int main(){
} int x,y,z;
x = 5, y = 4;
z = sum(x,y);
printf(“Sum is %d:”,z};
return 0;
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Pros and Cons of using
Functions
Advantages Disadvantages

• Modularization • Reduced execution speed

• Code Reusability • Every function call adds an additional


overhead to the OS to create space for
• Reduced Coding time
it in the program memory.
• Easier to Debug • This slows down the program.

• Easier to understand

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Functions in Memory
How does function execution
look like in memory?

Let us recall our block diagram

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Our block diagram is back
again!
• OS loads the
program executable
into the RAM
• Executes it line by
line on CPU

A line Program
from exe Program Executable (P1)
(exe)
Program is Compiled
executed Executable
Program of P1 (exe)
on CPU
CPU Executable gets
line by line
loaded into the
RAM

Memory (RAM) DISK


Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Looking at the main memory
only
Stack Segment

Functions (and
Memory variables defined
allocated to in them) reside in
the our Heap Segment the stack
program segment of the
memory
Data Segment

Text Segment

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Functions in Memory
/* myProg.c */
#include <stdio.h>
Stack

int sum(int a, int b);


int sum(int a, int b)
{
int total;
total = a + b;
return total;
Heap

}
int main()
{
Data

int x,y,z;
x = 5, y = 4;
z = sum(x,y);
Text

printf(“Sum:%d”,z};
return 0;
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Functions in Memory
/* myProg.c */
Frame allocated to main() in #include <stdio.h>
x y z the stack
Stack

int sum(int a, int b);


int sum(int a, int b)
{
Variables x, y and z reside int total;
inside the stack frame total = a + b;
allocated to the function
return total;
Heap

main()
}
int main()
{
Data

int x,y,z;
x = 5, y = 4;
z = sum(x,y);
Text

printf(“Sum:%d”,z};
return 0;
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Functions in Memory
/* myProg.c */
Frame allocated to main() in #include <stdio.h>
x y z the stack
Stack

int sum(int a, int b);


Frame allocated to sum() in
a b total int sum(int a, int b)
the stack
{
Variables x, y and z reside int total;
inside the stack frame total = a + b;
allocated to the function
return total;
Heap

main()
}
Variables a, b and total int main()
reside in the stack frame {
Data

allocated to the function int x,y,z;


sum()
x = 5, y = 4;
z = sum(x,y);
Text

printf(“Sum:%d”,z};
return 0;
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Functions in Memory
/* myProg.c */
Frame allocated to main() in #include <stdio.h>
x y z the stack
Stack

int sum(int a, int b);


Frame allocated to sum() in
a b total int sum(int a, int b)
the stack
{
When function sum() returns, int total;
frame allocated to it is total = a + b;
destroyed. So, a, b and total return total;
Heap

are destroyed
}
int main()
{
Data

int x,y,z;
x = 5, y = 4;
z = sum(x,y);
Text

printf(“Sum:%d”,z};
return 0;
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Functions in Memory
/* myProg.c */
Frame allocated to main() in #include <stdio.h>
x y z the stack
Stack

int sum(int a, int b);


Frame allocated to sum() in
a b total int sum(int a, int b)
the stack
{
When function sum() returns, int total;
frame allocated to it is total = a + b;
destroyed. So, a, b and total return total;
Heap

are destroyed.
}
When function main() int main()
returns or the program {
Data

terminates, the entire int x,y,z;


memory allocated to this
program is destroyed.
x = 5, y = 4;
z = sum(x,y);
Text

printf(“Sum:%d”,z};
return 0;
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Call by Value
Swap two numbers and
“Call by Value”
int main()
void swap(int a, int b)
{
{
int x, y;
int c = a;
printf(“Enter the numbers:\n”);
a = b;
scanf(“%d %d”, &x, &y);
b = c;
swap(x, y);
printf(“a=%d, b=%d\n”, a,b);
printf(“x=%d, y=%d\n”,x,y);
}
return 0;
}
Call by value:
Program Execution:
• When a function is being called, the values of the actual arguments from Enter the numbers:
caller function are copied into the formal parameters of the called 45
function. a=5, b=4
• Values of x and y are copied into a and b respectively
x=4, y=5
• Any change to the values of a and b is not reflected into x and y
• a and b are swapped in the swap() function. This swap is not reflected in x
and y
• printf statement in swap() function prints the swapped values of a & b
• printf statement in main() function prints the old values of x and y
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

More Examples and Exercises


Examples (Work out)

Example 1:
Write a function factn() which accepts input n and computes n!
Write the relevant code in main() to call this function.

Example 2: (Code)
Write a C program to compute the sum of the series
1 + 2^2 + 3^3 + … n^n (where n is user input).
Use a function long compute_sum(int) to compute the sum
of the series, and within it, call another function long
power(int) to compute the term i^i for each i

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Exercise: Execute both the
programs and observe the output
void f1(int); int f1(int);
int f2(); int f2(int);
int main() { int main(){
f1(f2()); printf("%d\n",f1(f2(f1(15))));
return 0; return 0;
} }
void f1(int a){ int f1(int a){
printf("%d",a); return f2(a/2);
} }
int f2(){ int f2(int a){
return 5; return a>5?a:5;
} }

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Pre-defined Functions
• printf() function

int printf("format string",argument_list);

• scanf() function

int scanf("format string",argument_list);

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Pre-defined Functions
• exit() function

#include<stdio.h>
#include<stdlib.h>
int main() {
//Program code
...
...
if (errorCondition) {
printf("An error occurred.\n");
exit(EXIT_FAILURE); // Terminate the entire program with a failure status
}
// More program code
...
...
return 0; // Return from the main function with a success status
}

Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Thank you
Q&A

You might also like