SlideShare a Scribd company logo
Lecture 5 - Functions in C
CSE 1102: Structured Programming Language
Instructor Name: Salim Shadman Ankur
Date: 11 April 2025
Introduction to Functions

A function is a block of code that performs a specific task.

Functions promote code reuse and modular programming.

Syntax: return_type function_name(parameters) { ... }

Example: int sum(int a, int b) { return a + b; }
Introduction to Functions
• A function in C is a block of organized reusuable code that is performs a
single related action. Every C program has at least one function, which is
main(), and all the most trivial programs can define additional functions.
• When the algorithm of a certain problem involves long and complex logic,
it is broken into smaller, independent and reusable blocks. These small
blocks of code are known by different names in different programming
languages such as a module, a subroutine, a function or a method.
• You can divide up your code into separate functions. How you divide up
your code among different functions is up to you, but logically the division
is such that each function performs a specific task.
Modular Programming
Functions are designed to perform a specific task that is a part of an entire process.
This approach towards software development is called modular programming.
Modular programming takes a top-down approach towards software development. The
programming solution has a main routine through which smaller independent modules
(functions) are called upon.
Each function is a separate, complete and reusable software component. When called,
a function performs a specified task and returns the control back to the calling routine,
optionally along with result of its process.
The main advantage of this approach is that the code becomes easy to follow, develop
and maintain.
Library Functions in C
C offers a number of library functions included in different header files. For
example, the stdio.h header file includes printf() and scanf() functions.
Similarly, the math.h header file includes a number of functions such as sin(),
pow(), sqrt() and more.
These functions perform a predefined task and can be called upon in any
program as per requirement.
However, if you don't find a suitable library function to serve your purpose,
you can define one.
Defining a Function in C
In C, it is necessary to provide the forward declaration of the prototype of any
function. The prototype of a library function is present in the corresponding
header file.
For a user-defined function, its prototype is present in the current program.
The definition of a function and its prototype declaration should match.
After all the statements in a function are executed, the flow of the program
returns to the calling environment. The function may return some data along
with the flow control.
Function Declaration & Definition
• Declaration tells the compiler about the function's name, return type, and parameters.
• Definition provides the actual body of the function.
• Declaration: int add(int, int);
• Definition: int add(int a, int b) { return a + b; }
• A function declaration tells the compiler about a function's name, return type, and
parameters.
• A function definition provides the actual body of the function.
• The C standard library provides numerous built-in functions that your program can call.
• For example, strcat() to concatenate two strings, strcpy() to copy one memory location to
another location, and many more functions.
• A function declaration is required when you define a function in one source file and you call
that function in another file. In such cases, you should declare the function at the top of the
file calling the function.
Parts in a Function
The general form of a function definition in C programming language is as
follows −
return_type function_name(parameter list)
{
body of the function
}
Parts in a Function
A function definition in C programming consists of a function header and a function body. Here are all the parts
of a function −
 Return Type − A function may return a value. The return_type is the data type of the value the function
returns. Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
 Argument List − An argument (also called parameter) is like a placeholder. When a function is invoked, you
pass a value as a parameter. This value is referred to as the actual parameter or argument. The parameter
list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is,
a function may contain no parameters.
 Function Body − The function body contains a collection of statements that defines what the function
does.
A function in C should have a return type. The type of the variable returned by the function must be the return
type of the function. In the above figure, the add() function returns an int type.
Example: User-defined Function in C
In this program, we have used a user-defined function called max(). This function takes two parameters num1
and num2 and returns the maximum value between the two −
#include <stdio.h>
/* function returning the max between two numbers */
int max(int num1, int num2){
/* local variable declaration */
int result;
if(num1 > num2)
result = num1;
else
result = num2;
return result;
}
Example: User-defined Function in C
int main(){
printf("Comparing two numbers using max() function: n");
printf("Which of the two, 75 or 57, is greater than the other? n");
printf("The answer is: %d", max(75, 57));
return 0;
}
Output:
When you runt this code, it will produce the following output −
Comparing two numbers using max() function:
Which of the two, 75 or 57, is greater than the other?
The answer is: 75
Calling Functions & Returning
Values
• Functions can be called from main or other functions.
• The value returned can be stored or used directly.
• Example: int result = add(10, 20);
• void functions do not return a value.
Calling Functions & Returning
Values
• While creating a C function, you give a definition of what the function has to do. To use a function, you will
have to call that function to perform the defined task.
• To call a function properly, you need to comply with the declaration of the function prototype. If the
function is defined to receive a set of arguments, the same number and type of arguments must be
passed.
• When a function is defined with arguments, the arguments in front of the function name are called formal
arguments. When a function is called, the arguments passed to it are the actual arguments.
• When a program calls a function, the program control is transferred to the called function. A called
function performs a defined task and when its return statement is executed or when its function-ending
closing brace is reached, it returns the program control back to the main program.
The main() Function in C

A C program is a collection of one or more functions, but one of the functions must be named as main(),
which is the entry point of the execution of the program.

From inside the main() function, other functions are called. The main() function can call a library function
such as printf(), whose prototype is fetched from the header file (stdio.h) or any other user-defined function
present in the code.

In C, the order of definition of the program is not material. In a program, wherever there is main(), it is the
entry point irrespective of whether it is the first function or not.

The main() function in C is an entry point of any program. The program execution starts with the main()
function. It is designed to perform the main processing of the program and clean up any resources that were
allocated by the program. In a C code, there may be any number of functions, but it must have a main()
function. Irrespective of its place in the code, it is the first function to be executed.

Note: In C, any function can call any other function, any number of times. A function can call itself too. Such
a self-calling function is called a recursive function..
The main() Function in C

The program's execution starts from the main() function as it is an entry point of the program, it starts
executing the statements written inside it. Other functions within the source program are defined to
perform certain task. The main function can call any of these functions. When main calls another function, it
passes execution control to the function, optionally passing the requisite number and type of arguments, so
that execution begins at the first statement in the called function. The called function returns control to
main when a return statement is executed or when the end of the function is reached. Note that return
statement is implicitly present as the last statement when its return type is int.

A program usually stops executing when it returns from or reaches the end of main, although it can
terminate at other points in the program for various reasons. For example, you may want to force the
termination of your program when some error condition is detected. To do so, you can use the exit function.
The main() Function in C

A C program must have a main() function.

The main is not a C keyword.

It is classified as a user-defined function because its body is not pre−decided, it depends on the processing
logic of the program.

By convention, int is the return type of main(). The last statement in the function body of main() returns 0, to
indicate that the function has been successfully executed. Any non−zero return value indicates failure.

Some old C compilers let you define main() function with void return type.

However, this is considered to be non−standard and is not recommended.

As compared to other functions, the main() function:

Can't be declared as inline.

Can't be declared as static.

Can't have its address taken.

Can't be called from your program.
Function Arguments

If a function is to use arguments, it must declare variables that accept the values of
the arguments. These variables are called the formal parameters of the function.

Formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
Call by Value vs Call by Reference
While calling a function, there are two ways in which arguments can be passed to a function −
1) Call by value
This method copies the actual value of an argument into the formal parameter of the function. In this case,
changes made to the parameter inside the function have no effect on the argument.
2) Call by reference
This method copies the address of an argument into the formal parameter. Inside the function, the address is
used to access the actual argument used in the call. This means that changes made to the parameter affect the
argument.
By default, C uses call by value to pass arguments. In general, it means the code within a function cannot alter
the arguments used to call the function.
Call by Value vs Call by Reference
• Call by value: Copy of actual parameter is passed.
• Changes do not affect the original variable.
• Call by reference: Address is passed using pointers.
• Changes affect the original variable.
Call by Value
You must know the terminologies to understand how the call by value method works −
• Formal arguments − A function needs certain data to perform its desired process.
When a function is defined, it is assumed that the data values will be provided in
the form of parameter or argument list inside the parenthesis in front of the
function name. These arguments are the variables of a certain data type.
• Actual arguments − When a certain function is to be called, it should be provided
with the required number of values of the same type and in the same sequence as
used in its definition.
Call by Value
Take a look at the following snippet −
type function_name(type var1, type var2, ...)
Here, the argument variables are called the formal arguments. Inside the functions
scope, these variables act as its local variables.
Consider the following function −
int add(int x, int y){
int z = x + y;
return z;
}
The arguments x and y in this function definition are the formal arguments.
Call by Value
Example: Call by Value in C
If the add() function is called, as shown in the code below, then the variables inside the parenthesis (a and b) are the actual
arguments. They are passed to the function.
Take a look at the following example −
#include <stdio.h>
int add(int x, int y){
int z = x + y;
return z;
}
int main(){
int a = 10, b = 20;
int c = add(a, b);
printf("Addition: %d", c);
}
When you run this code, it will produce the following output −
Addition: 30
Call by Value
The Call by Value method implies that the values of the actual arguments are copied
in the formal argument variables. Hence, "x" takes the value of "a" and "b" is
assigned to "y". The local variable "z" inside the add() function stores the addition
value. In the main() function, the value returned by the add() function is assigned to
"c", which is printed.
Note that a variable in C language is a named location in the memory. Hence,
variables are created in the memory and each variable is assigned a random
memory address by the compiler.
Call by Value is the default function calling mechanism in C. It eliminates a functions
potential side effects, making your software simpler to maintain and easy to
understand. It is best suited for a function expected to do a certain computation on
the argument received and return the result.
Call by Value (Example)
#include <stdio.h>
/* function declaration */
void swap(int x, int y);
int main(){
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a: %dn", a);
printf("Before swap, value of b: %dn", b);
/* calling a function to swap the values */
swap(a, b);
printf("After swap, value of a: %dn", a);
printf("After swap, value of b: %dn", b);
return 0;
}
Call by Value (Example)
void swap(int x, int y){
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
Output
When you run this code, it will produce the following output −
Before swap, value of a: 100
Before swap, value of b: 200
After swap, value of a: 100
After swap, value of b: 200
Call by Value (Example)
 It shows that there are no changes in the values, although they had been changed inside the function.
 Since the values are copied in different local variables of another function, any manipulation doesnt have
any effect on the actual argument variables in the calling function.
 However, the Call by Value method is less efficient when we need to pass large objects such as an array or a
file to another function. Also, in some cases, we may need the actual arguments to be manipulated by
another function. In such cases, the Call by Value mechanism is not useful.
Recursion
• A function that calls itself is called a recursive function.
• Used to solve problems that can be broken down into sub-problems.
• Example: Factorial function.
• Must include base case to stop recursion.
• Recursion is the process by which a function calls itself. C language allows
writing of such functions which call itself to solve complicated problems by
breaking them down into simple and easy problems. These functions are
known as recursive functions.
Why Recursion is Used in C?
Recursion is used to perform complex tasks such as tree and graph structure
traversals. Popular recursive programming solutions include factorial, binary
search, tree traversal, tower of Hanoi, eight queens problem in chess, etc.
A recursive program becomes concise, it is not easily comprehendible. Even
if the size of the code may reduce, it needs more resources of the processor,
as it involves multiple IO calls to the function.
Factorial using Recursion
#include <stdio.h>
#include <math.h>
/* function declaration */
int factorial(int i){
if(i <= 1){
return 1;
}
return i * factorial(i - 1);
}
int main(){
int a = 5;
int f = factorial(a);
printf("a: %d n", a);
printf("Factorial of a: %d", f);
return 0;
}
Output
Run the code and check
its output −
a: 5
Factorial of a: 120
Fibonacci using Recursion
#include <stdio.h>
int fibonacci(int i){
if(i == 0){
return 0;
}
if(i == 1){
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main(){
int i;
for (i = 0; i < 10; i++){
printf("%dtn", fibonacci(i));
}
return 0;
}
Output
−
0
1
1
2
3
5
8
13
21
34
Recursion
A recursive function in C is a function that calls itself. A recursive function is used when a certain problem is defined in
terms of itself. Although it involves iteration, using iterative approach to solve such problems can be tedious. Recursive
approach provides a very concise solution to seemingly complex problems.
Syntax:
This is how a general recursive function looks like −
void recursive_function(){
recursion(); // function calls itself
}
int main(){
recursive_function();
}
While using recursion, programmers need to be careful to define an exit condition from the function, otherwise it
will go into an infinite loop.
Storage Classes
C storage classes define the scope (visibility) and lifetime of variables and/or
functions within a C Program. They precede the type that they modify.
We have four different storage classes in a C program −
• auto: Default storage class for local variables.
• static: Retains value between function calls.
• extern: Refers to a global variable defined elsewhere.
• register: Stores variable in CPU register for faster access.
The auto Storage Classes
The auto is a default storage class for all variables that are declared inside a function or a
block. The keyword "auto", which is optional, can be used to define local variables.
The scope and lifetime of auto variables are within the same block in which they are declared.
Example of auto Storage Class
The following code statements demonstrate the declaration of an automatic (auto) variable −
{
int mount;
auto int month;
}
The example above defines two variables with in the same storage class. 'auto' can only be
used within functions, i.e., local variables.
The register Storage Classes
The register storage class is used to define local variables that should be stored in a
register instead of RAM. This means that the variable has a maximum size equal to the
register size (usually one word) and can't have the unary '&' operator applied to it (as it
does not have a memory location).
The register should only be used for variables that require quick access such as
counters. It should also be noted that defining 'register' does not mean that the variable
will be stored in a register. It means that it MIGHT be stored in a register depending on
hardware and implementation restrictions.
Example of register Storage Class
The following code statement demonstrates the declaration of a register variable −
{
register int miles;
}
The static Storage Classes
The static storage class instructs the compiler to keep a local variable in
existence during the life-time of the program instead of creating and
destroying it each time it comes into and goes out of scope. Therefore,
making local variables static allows them to maintain their values between
function calls.
The static modifier may also be applied to global variables. When this is
done, it causes that variable's scope to be restricted to the file in which it is
declared.
In C programming, when static is used on a global variable, it causes only
one copy of that member to be shared by all the objects of its class.
The static Storage Classes
Example of static Storage Class
The following example demonstrates the use of a static storage class in a C program −
#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main(){
while(count--) {
func();
}
return 0;
}
/* function definition */
void func(void) {
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %dn", i, count);
}
Output
When the above code is compiled
and executed, it produces the
following result −
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
The extern Storage Classes
 The extern storage class is used to give a reference of a global variable that is visible to ALL the
program files. When you use 'extern', the variable cannot be initialized however, it points the
variable name at a storage location that has been previously defined.
 When you have multiple files and you define a global variable or function, which will also be used
in other files, then extern will be used in another file to provide the reference of defined variable or
function. Just for understanding, extern is used to declare a global variable or function in another
file.
 The extern modifier is most commonly used when there are two or more files sharing the same
global variables or functions as explained below.
 Example of extern Storage Class
 The example of an extern storage class may contain two or more files. Here is an example
demonstrating the use of an extern storage class in C language −
The extern Storage Classes
First File: main.c
#include <stdio.h>
int count;
extern void write_extern();
main(){
count = 5;
write_extern();
}
The extern Storage Classes
Second File: support.c
#include <stdio.h>
extern int count;
void write_extern(void) {
printf("Count is %dn", count);
}
Here, extern is being used to declare count in the second file, whereas it has its definition in the first file (main.c). Now, compile these two
files as follows −
$gcc main.c support.c
It will produce the executable program a.out. When this program is executed, it will produce the following output −
Count is 5
Exercises
1) Write a function to calculate factorial of a number.
2) Create a recursive function to compute Fibonacci sequence.
3) Write a program using static variable in a function.
4) Demonstrate extern keyword with two functions.
Ad

More Related Content

Similar to Lecture_5_-_Functions_in_C_Detailed.pptx (20)

Functions
Functions Functions
Functions
Dr.Subha Krishna
 
Functions and Header files ver very useful
Functions and Header files ver very usefulFunctions and Header files ver very useful
Functions and Header files ver very useful
RamSiddesh1
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
Muhammad Hammad Waseem
 
Programming in C FUNCTION Basic concepts.pptx
Programming in C FUNCTION Basic concepts.pptxProgramming in C FUNCTION Basic concepts.pptx
Programming in C FUNCTION Basic concepts.pptx
vengaimarbhan1
 
C FUNCTIONS
C FUNCTIONSC FUNCTIONS
C FUNCTIONS
TeenaGeorge15
 
Functions-Computer programming
Functions-Computer programmingFunctions-Computer programming
Functions-Computer programming
nmahi96
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
Hattori Sidek
 
Functions assignment
Functions assignmentFunctions assignment
Functions assignment
Ahmad Kamal
 
Function
FunctionFunction
Function
Rajat Patel
 
structured Programming Unit-7-Functions.pptx
structured Programming Unit-7-Functions.pptxstructured Programming Unit-7-Functions.pptx
structured Programming Unit-7-Functions.pptx
SuryaBasnet1
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
YOGESH SINGH
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
Shuvongkor Barman
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
Sampath Kumar
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
Venkatesh Goud
 
cp Module4(1)
cp Module4(1)cp Module4(1)
cp Module4(1)
Amarjith C K
 
Module 3-Functions
Module 3-FunctionsModule 3-Functions
Module 3-Functions
nikshaikh786
 
C functions by ranjan call by value and reference.pptx
C functions by ranjan call by value and reference.pptxC functions by ranjan call by value and reference.pptx
C functions by ranjan call by value and reference.pptx
ranjan317165
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
vekariyakashyap
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
KhurramKhan173
 
functions in c language_functions in c language.pptx
functions in c language_functions in c language.pptxfunctions in c language_functions in c language.pptx
functions in c language_functions in c language.pptx
MehakBhatia38
 
Functions and Header files ver very useful
Functions and Header files ver very usefulFunctions and Header files ver very useful
Functions and Header files ver very useful
RamSiddesh1
 
Programming in C FUNCTION Basic concepts.pptx
Programming in C FUNCTION Basic concepts.pptxProgramming in C FUNCTION Basic concepts.pptx
Programming in C FUNCTION Basic concepts.pptx
vengaimarbhan1
 
Functions-Computer programming
Functions-Computer programmingFunctions-Computer programming
Functions-Computer programming
nmahi96
 
Functions assignment
Functions assignmentFunctions assignment
Functions assignment
Ahmad Kamal
 
structured Programming Unit-7-Functions.pptx
structured Programming Unit-7-Functions.pptxstructured Programming Unit-7-Functions.pptx
structured Programming Unit-7-Functions.pptx
SuryaBasnet1
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
YOGESH SINGH
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
Shuvongkor Barman
 
Module 3-Functions
Module 3-FunctionsModule 3-Functions
Module 3-Functions
nikshaikh786
 
C functions by ranjan call by value and reference.pptx
C functions by ranjan call by value and reference.pptxC functions by ranjan call by value and reference.pptx
C functions by ranjan call by value and reference.pptx
ranjan317165
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
vekariyakashyap
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
KhurramKhan173
 
functions in c language_functions in c language.pptx
functions in c language_functions in c language.pptxfunctions in c language_functions in c language.pptx
functions in c language_functions in c language.pptx
MehakBhatia38
 

More from Salim Shadman Ankur (9)

CSE 1102 - Lecture_8 - Pointers_in_C.pptx
CSE 1102 - Lecture_8 - Pointers_in_C.pptxCSE 1102 - Lecture_8 - Pointers_in_C.pptx
CSE 1102 - Lecture_8 - Pointers_in_C.pptx
Salim Shadman Ankur
 
CSE 1102 - Lecture_7 - Strings_in_C.pptx
CSE 1102 - Lecture_7 - Strings_in_C.pptxCSE 1102 - Lecture_7 - Strings_in_C.pptx
CSE 1102 - Lecture_7 - Strings_in_C.pptx
Salim Shadman Ankur
 
CSE 1102 - Lecture 6 - Arrays in C .pptx
CSE 1102 - Lecture 6 - Arrays in C .pptxCSE 1102 - Lecture 6 - Arrays in C .pptx
CSE 1102 - Lecture 6 - Arrays in C .pptx
Salim Shadman Ankur
 
CSE 1102 - Lecture 2 - C Control Statements.pptx
CSE 1102 - Lecture 2 - C Control Statements.pptxCSE 1102 - Lecture 2 - C Control Statements.pptx
CSE 1102 - Lecture 2 - C Control Statements.pptx
Salim Shadman Ankur
 
CSE 1102 - Lecture 1 - C Fundamentals.pptx
CSE 1102 - Lecture 1 - C Fundamentals.pptxCSE 1102 - Lecture 1 - C Fundamentals.pptx
CSE 1102 - Lecture 1 - C Fundamentals.pptx
Salim Shadman Ankur
 
Job4CSE (System Development Project)
Job4CSE (System Development Project)Job4CSE (System Development Project)
Job4CSE (System Development Project)
Salim Shadman Ankur
 
Opportunistic approach (iterative prototyping)
Opportunistic approach (iterative prototyping) Opportunistic approach (iterative prototyping)
Opportunistic approach (iterative prototyping)
Salim Shadman Ankur
 
Builder design pattern
Builder design patternBuilder design pattern
Builder design pattern
Salim Shadman Ankur
 
11 15 (doubly linked list)
11 15 (doubly linked list)11 15 (doubly linked list)
11 15 (doubly linked list)
Salim Shadman Ankur
 
CSE 1102 - Lecture_8 - Pointers_in_C.pptx
CSE 1102 - Lecture_8 - Pointers_in_C.pptxCSE 1102 - Lecture_8 - Pointers_in_C.pptx
CSE 1102 - Lecture_8 - Pointers_in_C.pptx
Salim Shadman Ankur
 
CSE 1102 - Lecture_7 - Strings_in_C.pptx
CSE 1102 - Lecture_7 - Strings_in_C.pptxCSE 1102 - Lecture_7 - Strings_in_C.pptx
CSE 1102 - Lecture_7 - Strings_in_C.pptx
Salim Shadman Ankur
 
CSE 1102 - Lecture 6 - Arrays in C .pptx
CSE 1102 - Lecture 6 - Arrays in C .pptxCSE 1102 - Lecture 6 - Arrays in C .pptx
CSE 1102 - Lecture 6 - Arrays in C .pptx
Salim Shadman Ankur
 
CSE 1102 - Lecture 2 - C Control Statements.pptx
CSE 1102 - Lecture 2 - C Control Statements.pptxCSE 1102 - Lecture 2 - C Control Statements.pptx
CSE 1102 - Lecture 2 - C Control Statements.pptx
Salim Shadman Ankur
 
CSE 1102 - Lecture 1 - C Fundamentals.pptx
CSE 1102 - Lecture 1 - C Fundamentals.pptxCSE 1102 - Lecture 1 - C Fundamentals.pptx
CSE 1102 - Lecture 1 - C Fundamentals.pptx
Salim Shadman Ankur
 
Job4CSE (System Development Project)
Job4CSE (System Development Project)Job4CSE (System Development Project)
Job4CSE (System Development Project)
Salim Shadman Ankur
 
Opportunistic approach (iterative prototyping)
Opportunistic approach (iterative prototyping) Opportunistic approach (iterative prototyping)
Opportunistic approach (iterative prototyping)
Salim Shadman Ankur
 
Ad

Recently uploaded (20)

Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Ad

Lecture_5_-_Functions_in_C_Detailed.pptx

  • 1. Lecture 5 - Functions in C CSE 1102: Structured Programming Language Instructor Name: Salim Shadman Ankur Date: 11 April 2025
  • 2. Introduction to Functions  A function is a block of code that performs a specific task.  Functions promote code reuse and modular programming.  Syntax: return_type function_name(parameters) { ... }  Example: int sum(int a, int b) { return a + b; }
  • 3. Introduction to Functions • A function in C is a block of organized reusuable code that is performs a single related action. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. • When the algorithm of a certain problem involves long and complex logic, it is broken into smaller, independent and reusable blocks. These small blocks of code are known by different names in different programming languages such as a module, a subroutine, a function or a method. • You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task.
  • 4. Modular Programming Functions are designed to perform a specific task that is a part of an entire process. This approach towards software development is called modular programming. Modular programming takes a top-down approach towards software development. The programming solution has a main routine through which smaller independent modules (functions) are called upon. Each function is a separate, complete and reusable software component. When called, a function performs a specified task and returns the control back to the calling routine, optionally along with result of its process. The main advantage of this approach is that the code becomes easy to follow, develop and maintain.
  • 5. Library Functions in C C offers a number of library functions included in different header files. For example, the stdio.h header file includes printf() and scanf() functions. Similarly, the math.h header file includes a number of functions such as sin(), pow(), sqrt() and more. These functions perform a predefined task and can be called upon in any program as per requirement. However, if you don't find a suitable library function to serve your purpose, you can define one.
  • 6. Defining a Function in C In C, it is necessary to provide the forward declaration of the prototype of any function. The prototype of a library function is present in the corresponding header file. For a user-defined function, its prototype is present in the current program. The definition of a function and its prototype declaration should match. After all the statements in a function are executed, the flow of the program returns to the calling environment. The function may return some data along with the flow control.
  • 7. Function Declaration & Definition • Declaration tells the compiler about the function's name, return type, and parameters. • Definition provides the actual body of the function. • Declaration: int add(int, int); • Definition: int add(int a, int b) { return a + b; } • A function declaration tells the compiler about a function's name, return type, and parameters. • A function definition provides the actual body of the function. • The C standard library provides numerous built-in functions that your program can call. • For example, strcat() to concatenate two strings, strcpy() to copy one memory location to another location, and many more functions. • A function declaration is required when you define a function in one source file and you call that function in another file. In such cases, you should declare the function at the top of the file calling the function.
  • 8. Parts in a Function The general form of a function definition in C programming language is as follows − return_type function_name(parameter list) { body of the function }
  • 9. Parts in a Function A function definition in C programming consists of a function header and a function body. Here are all the parts of a function −  Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.  Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.  Argument List − An argument (also called parameter) is like a placeholder. When a function is invoked, you pass a value as a parameter. This value is referred to as the actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.  Function Body − The function body contains a collection of statements that defines what the function does. A function in C should have a return type. The type of the variable returned by the function must be the return type of the function. In the above figure, the add() function returns an int type.
  • 10. Example: User-defined Function in C In this program, we have used a user-defined function called max(). This function takes two parameters num1 and num2 and returns the maximum value between the two − #include <stdio.h> /* function returning the max between two numbers */ int max(int num1, int num2){ /* local variable declaration */ int result; if(num1 > num2) result = num1; else result = num2; return result; }
  • 11. Example: User-defined Function in C int main(){ printf("Comparing two numbers using max() function: n"); printf("Which of the two, 75 or 57, is greater than the other? n"); printf("The answer is: %d", max(75, 57)); return 0; } Output: When you runt this code, it will produce the following output − Comparing two numbers using max() function: Which of the two, 75 or 57, is greater than the other? The answer is: 75
  • 12. Calling Functions & Returning Values • Functions can be called from main or other functions. • The value returned can be stored or used directly. • Example: int result = add(10, 20); • void functions do not return a value.
  • 13. Calling Functions & Returning Values • While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. • To call a function properly, you need to comply with the declaration of the function prototype. If the function is defined to receive a set of arguments, the same number and type of arguments must be passed. • When a function is defined with arguments, the arguments in front of the function name are called formal arguments. When a function is called, the arguments passed to it are the actual arguments. • When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.
  • 14. The main() Function in C  A C program is a collection of one or more functions, but one of the functions must be named as main(), which is the entry point of the execution of the program.  From inside the main() function, other functions are called. The main() function can call a library function such as printf(), whose prototype is fetched from the header file (stdio.h) or any other user-defined function present in the code.  In C, the order of definition of the program is not material. In a program, wherever there is main(), it is the entry point irrespective of whether it is the first function or not.  The main() function in C is an entry point of any program. The program execution starts with the main() function. It is designed to perform the main processing of the program and clean up any resources that were allocated by the program. In a C code, there may be any number of functions, but it must have a main() function. Irrespective of its place in the code, it is the first function to be executed.  Note: In C, any function can call any other function, any number of times. A function can call itself too. Such a self-calling function is called a recursive function..
  • 15. The main() Function in C  The program's execution starts from the main() function as it is an entry point of the program, it starts executing the statements written inside it. Other functions within the source program are defined to perform certain task. The main function can call any of these functions. When main calls another function, it passes execution control to the function, optionally passing the requisite number and type of arguments, so that execution begins at the first statement in the called function. The called function returns control to main when a return statement is executed or when the end of the function is reached. Note that return statement is implicitly present as the last statement when its return type is int.  A program usually stops executing when it returns from or reaches the end of main, although it can terminate at other points in the program for various reasons. For example, you may want to force the termination of your program when some error condition is detected. To do so, you can use the exit function.
  • 16. The main() Function in C  A C program must have a main() function.  The main is not a C keyword.  It is classified as a user-defined function because its body is not pre−decided, it depends on the processing logic of the program.  By convention, int is the return type of main(). The last statement in the function body of main() returns 0, to indicate that the function has been successfully executed. Any non−zero return value indicates failure.  Some old C compilers let you define main() function with void return type.  However, this is considered to be non−standard and is not recommended.  As compared to other functions, the main() function:  Can't be declared as inline.  Can't be declared as static.  Can't have its address taken.  Can't be called from your program.
  • 17. Function Arguments  If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.  Formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.
  • 18. Call by Value vs Call by Reference While calling a function, there are two ways in which arguments can be passed to a function − 1) Call by value This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. 2) Call by reference This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. By default, C uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function.
  • 19. Call by Value vs Call by Reference • Call by value: Copy of actual parameter is passed. • Changes do not affect the original variable. • Call by reference: Address is passed using pointers. • Changes affect the original variable.
  • 20. Call by Value You must know the terminologies to understand how the call by value method works − • Formal arguments − A function needs certain data to perform its desired process. When a function is defined, it is assumed that the data values will be provided in the form of parameter or argument list inside the parenthesis in front of the function name. These arguments are the variables of a certain data type. • Actual arguments − When a certain function is to be called, it should be provided with the required number of values of the same type and in the same sequence as used in its definition.
  • 21. Call by Value Take a look at the following snippet − type function_name(type var1, type var2, ...) Here, the argument variables are called the formal arguments. Inside the functions scope, these variables act as its local variables. Consider the following function − int add(int x, int y){ int z = x + y; return z; } The arguments x and y in this function definition are the formal arguments.
  • 22. Call by Value Example: Call by Value in C If the add() function is called, as shown in the code below, then the variables inside the parenthesis (a and b) are the actual arguments. They are passed to the function. Take a look at the following example − #include <stdio.h> int add(int x, int y){ int z = x + y; return z; } int main(){ int a = 10, b = 20; int c = add(a, b); printf("Addition: %d", c); } When you run this code, it will produce the following output − Addition: 30
  • 23. Call by Value The Call by Value method implies that the values of the actual arguments are copied in the formal argument variables. Hence, "x" takes the value of "a" and "b" is assigned to "y". The local variable "z" inside the add() function stores the addition value. In the main() function, the value returned by the add() function is assigned to "c", which is printed. Note that a variable in C language is a named location in the memory. Hence, variables are created in the memory and each variable is assigned a random memory address by the compiler. Call by Value is the default function calling mechanism in C. It eliminates a functions potential side effects, making your software simpler to maintain and easy to understand. It is best suited for a function expected to do a certain computation on the argument received and return the result.
  • 24. Call by Value (Example) #include <stdio.h> /* function declaration */ void swap(int x, int y); int main(){ /* local variable definition */ int a = 100; int b = 200; printf("Before swap, value of a: %dn", a); printf("Before swap, value of b: %dn", b); /* calling a function to swap the values */ swap(a, b); printf("After swap, value of a: %dn", a); printf("After swap, value of b: %dn", b); return 0; }
  • 25. Call by Value (Example) void swap(int x, int y){ int temp; temp = x; /* save the value of x */ x = y; /* put y into x */ y = temp; /* put temp into y */ return; } Output When you run this code, it will produce the following output − Before swap, value of a: 100 Before swap, value of b: 200 After swap, value of a: 100 After swap, value of b: 200
  • 26. Call by Value (Example)  It shows that there are no changes in the values, although they had been changed inside the function.  Since the values are copied in different local variables of another function, any manipulation doesnt have any effect on the actual argument variables in the calling function.  However, the Call by Value method is less efficient when we need to pass large objects such as an array or a file to another function. Also, in some cases, we may need the actual arguments to be manipulated by another function. In such cases, the Call by Value mechanism is not useful.
  • 27. Recursion • A function that calls itself is called a recursive function. • Used to solve problems that can be broken down into sub-problems. • Example: Factorial function. • Must include base case to stop recursion. • Recursion is the process by which a function calls itself. C language allows writing of such functions which call itself to solve complicated problems by breaking them down into simple and easy problems. These functions are known as recursive functions.
  • 28. Why Recursion is Used in C? Recursion is used to perform complex tasks such as tree and graph structure traversals. Popular recursive programming solutions include factorial, binary search, tree traversal, tower of Hanoi, eight queens problem in chess, etc. A recursive program becomes concise, it is not easily comprehendible. Even if the size of the code may reduce, it needs more resources of the processor, as it involves multiple IO calls to the function.
  • 29. Factorial using Recursion #include <stdio.h> #include <math.h> /* function declaration */ int factorial(int i){ if(i <= 1){ return 1; } return i * factorial(i - 1); } int main(){ int a = 5; int f = factorial(a); printf("a: %d n", a); printf("Factorial of a: %d", f); return 0; } Output Run the code and check its output − a: 5 Factorial of a: 120
  • 30. Fibonacci using Recursion #include <stdio.h> int fibonacci(int i){ if(i == 0){ return 0; } if(i == 1){ return 1; } return fibonacci(i-1) + fibonacci(i-2); } int main(){ int i; for (i = 0; i < 10; i++){ printf("%dtn", fibonacci(i)); } return 0; } Output − 0 1 1 2 3 5 8 13 21 34
  • 31. Recursion A recursive function in C is a function that calls itself. A recursive function is used when a certain problem is defined in terms of itself. Although it involves iteration, using iterative approach to solve such problems can be tedious. Recursive approach provides a very concise solution to seemingly complex problems. Syntax: This is how a general recursive function looks like − void recursive_function(){ recursion(); // function calls itself } int main(){ recursive_function(); } While using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop.
  • 32. Storage Classes C storage classes define the scope (visibility) and lifetime of variables and/or functions within a C Program. They precede the type that they modify. We have four different storage classes in a C program − • auto: Default storage class for local variables. • static: Retains value between function calls. • extern: Refers to a global variable defined elsewhere. • register: Stores variable in CPU register for faster access.
  • 33. The auto Storage Classes The auto is a default storage class for all variables that are declared inside a function or a block. The keyword "auto", which is optional, can be used to define local variables. The scope and lifetime of auto variables are within the same block in which they are declared. Example of auto Storage Class The following code statements demonstrate the declaration of an automatic (auto) variable − { int mount; auto int month; } The example above defines two variables with in the same storage class. 'auto' can only be used within functions, i.e., local variables.
  • 34. The register Storage Classes The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location). The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions. Example of register Storage Class The following code statement demonstrates the declaration of a register variable − { register int miles; }
  • 35. The static Storage Classes The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared. In C programming, when static is used on a global variable, it causes only one copy of that member to be shared by all the objects of its class.
  • 36. The static Storage Classes Example of static Storage Class The following example demonstrates the use of a static storage class in a C program − #include <stdio.h> /* function declaration */ void func(void); static int count = 5; /* global variable */ main(){ while(count--) { func(); } return 0; } /* function definition */ void func(void) { static int i = 5; /* local static variable */ i++; printf("i is %d and count is %dn", i, count); } Output When the above code is compiled and executed, it produces the following result − i is 6 and count is 4 i is 7 and count is 3 i is 8 and count is 2 i is 9 and count is 1 i is 10 and count is 0
  • 37. The extern Storage Classes  The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern', the variable cannot be initialized however, it points the variable name at a storage location that has been previously defined.  When you have multiple files and you define a global variable or function, which will also be used in other files, then extern will be used in another file to provide the reference of defined variable or function. Just for understanding, extern is used to declare a global variable or function in another file.  The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below.  Example of extern Storage Class  The example of an extern storage class may contain two or more files. Here is an example demonstrating the use of an extern storage class in C language −
  • 38. The extern Storage Classes First File: main.c #include <stdio.h> int count; extern void write_extern(); main(){ count = 5; write_extern(); }
  • 39. The extern Storage Classes Second File: support.c #include <stdio.h> extern int count; void write_extern(void) { printf("Count is %dn", count); } Here, extern is being used to declare count in the second file, whereas it has its definition in the first file (main.c). Now, compile these two files as follows − $gcc main.c support.c It will produce the executable program a.out. When this program is executed, it will produce the following output − Count is 5
  • 40. Exercises 1) Write a function to calculate factorial of a number. 2) Create a recursive function to compute Fibonacci sequence. 3) Write a program using static variable in a function. 4) Demonstrate extern keyword with two functions.