0% found this document useful (0 votes)
13 views32 pages

User-Defined Functions in C Programming

This document provides an introduction to user-defined functions in C programming, explaining their importance for code organization and reusability. It covers function categories, definitions, declarations, and examples of both library and user-defined functions. Additionally, it emphasizes the advantages of using functions, such as improved readability and easier debugging.
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)
13 views32 pages

User-Defined Functions in C Programming

This document provides an introduction to user-defined functions in C programming, explaining their importance for code organization and reusability. It covers function categories, definitions, declarations, and examples of both library and user-defined functions. Additionally, it emphasizes the advantages of using functions, such as improved readability and easier debugging.
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

Introduction to C Programming (B25PLA105)

MODULE - 04

User-defined Functions: Introduction, Need for User-defined Functions, A Multi-functional Program,


Elements of User-defined Functions, Definition of Function, Return Values and their Types, Function
Calls, Function Declaration, No Arguments and no Return Values, Arguments but no Return Values,
Nesting of Functions.

INTRODUCTION
One of the greatest strengths of the C programming language is its powerful support for functions. A function
is a well-structured block of statements designed to perform a specific task. Using functions makes a program
more organized, readable, modular, and easier to debug.
Until now, in most programs we wrote, we already used functions such as:
• main() — written by the programmer (user-defined)
• printf(), scanf() — built-in functions (library functions)
Most beginners don’t realize they are already using functions every time they call printf().
Real-Life Analogy
Think of a restaurant kitchen:

Real World Program Equivalent

Customer places order main()

Chef prepares food Function performing task

Different dishes prepared in separate sections Different independent functions

Menu items can be prepared again when needed Function can be called multiple times

You don’t need to tell the chef how to cook every time — similarly once a function is written, we just call it
whenever needed.
Categories of Functions
Functions in C are classified into two major categories:

Type of Function Examples Who Creates It?

Library Functions printf(), scanf(), sqrt(), Already written and provided by the C
strlen() library

User-Defined Functions main(), add(), max(), area() Created by the programmer


(UDFs)

Dept of CSE, RRCE 2025-26 1


Introduction to C Programming (B25PLA105)

Library functions are stored in header files such as <stdio.h>, <math.h>, <string.h>, etc. They are already
tested, reliable, and ready to use.
User-defined functions must be developed by the programmer while writing the program. Once created, they
can also be reused like library functions.
Program 1: Using a Library Function (sqrt())
#include <stdio.h>
#include <math.h>
int main() {
printf("Square root of 25 is: %f", sqrt(25));
return 0;
}
Output
Square root of 25 is: 5.000000
Explanation:
1. #include <stdio.h> allows us to use printf().
2. #include <math.h> is required because sqrt() belongs to math library.
3. sqrt(25) is the library function that calculates the square root of 25.
4. The result returned by sqrt() is passed to printf() for display.
5. The program ends with return 0;.
This program demonstrates using an already available function — the programmer did not define sqrt().

Program 2: Using a User-Defined Function


#include <stdio.h>
void displayMessage() {
printf("This is a user-defined function.");
}
int main() {
displayMessage();
return 0;
}

Dept of CSE, RRCE 2025-26 2


Introduction to C Programming (B25PLA105)

Output
This is a user-defined function.
Explanation:
• void displayMessage() is a user-defined function written by the programmer.
• It prints a message when called.
• Inside main(), the statement displayMessage(); tells the program to execute that function.
• After execution, control returns back to main().

Program 3: Using Both Library and User-Defined Functions


#include <stdio.h>
#include <math.h>
void line() {
printf("------------------------\n");
}
int main() {
line();
printf("Value of cos(0) is: %f\n", cos(0));
line();
return 0;
}
Output
------------------------
Value of cos(0) is: 1.000000
------------------------
Explanation:
• line() is a user-defined function that prints a line of hyphens.
• cos(0) is a library function from <math.h>.
• The program uses both types, demonstrating how C supports modular programming.

Dept of CSE, RRCE 2025-26 3


Introduction to C Programming (B25PLA105)

NEED FOR USER-DEFINED FUNCTIONS


Although a complete program can be written inside only the main() function, such programs soon become:
• Very long
• Difficult to understand
• Hard to debug
• Not reusable
To avoid these problems, C provides functions to divide a program into small, manageable parts.

Advantages of Using Functions

Advantage Meaning

Readability Code becomes easy to understand

Debugging Errors can be found in a specific function

Reusability Write once — use multiple times

Maintenance Updates affect only related parts

Teamwork Different programmers can work on different functions

Program 1: Without Functions (Bad Practice)


#include <stdio.h>
int main() {
printf("Hello\n");
printf("Hello\n");
printf("Hello\n");
Dept of CSE, RRCE 2025-26 4
Introduction to C Programming (B25PLA105)

return 0;
}
If we need 100 “Hello”, we must repeat the line 100 times — not practical.

Program 2: With Functions (Good Practice)


#include <stdio.h>
void printHello() {
printf("Hello\n");
}

int main() {
for(int i = 1; i <= 3; i++)
printHello();
return 0;
}
Explanation:
• The task (printing "Hello") is encapsulated inside a function.
• Repetition is controlled from main().

Program 3: Multiple Tasks Using Functions


#include <stdio.h>
void line() {
printf("--------------------\n");

void message() {
printf("Functions make programs easy!\n");
}
int main() {
line();
message();

Dept of CSE, RRCE 2025-26 5


Introduction to C Programming (B25PLA105)

line();
return 0;
}
Explanation:
• The program is more readable because each function performs a single meaningful task.

A MULTI-FUNCTIONAL PROGRAM
A function in C can be treated like a black box. The only thing the rest of the program knows is:
• What goes inside (input parameters)
• What comes out (return value)
The internal working of the function remains hidden. This idea supports abstraction — a key advantage of
functions.
When a function is called, the control of the program temporarily transfers to that function. Once execution
completes, control returns to the calling statement.
Example: printline() Function
This function prints a line of 39 hyphens.
Function Definition
void printline() {
for(int i = 1; i <= 39; i++)
printf("-");
}
Complete Program Using This Function
#include <stdio.h>
void printline();
int main() {
printline();
printf("\nThis illustrates the use of C functions\n");
printline();
return 0;
}

Dept of CSE, RRCE 2025-26 6


Introduction to C Programming (B25PLA105)

void printline() {
for(int i = 1; i <= 39; i++)
printf("-");
}
Output
---------------------------------------
This illustrates the use of C functions
---------------------------------------

Program 1: A Program With Two Functions Called in Sequence


#include <stdio.h>
void greet() {
printf("Hello User!\n");
}
void farewell() {
printf("Goodbye User!\n");
}
int main() {
greet();
farewell();

Dept of CSE, RRCE 2025-26 7


Introduction to C Programming (B25PLA105)

return 0;
}
Output:
Hello User!
Goodbye User!
Explanation:
• The main() function calls two user-defined functions: greet() and farewell().
• The control moves from main() → greet() → returns to main() → farewell() → returns to main().
• This demonstrates how multiple functions can be used in a single program.

Program 2: Function Calling Another Function


#include <stdio.h>
void stars() {
printf("***\n");
}
void display() {
stars();
printf("Message printed inside function\n");
stars();
}
int main() {
display();
return 0;
}
Output:
***
Message printed inside function
***
Explanation:
• main() calls display().

Dept of CSE, RRCE 2025-26 8


Introduction to C Programming (B25PLA105)

• Inside display(), another function stars() is called twice.


• This shows that functions can call other functions (not only main()).

Program 3: Using Function Inside Loop


#include <stdio.h>
void printLine() {
printf("---------------\n");
}
int main() {
for(int i=1; i<=3; i++)
printLine();
return 0;
}
Output:
---------------
---------------
---------------
Explanation:
• The function printLine() prints a line.
• The loop in main() calls the function three times.
• This demonstrates function reuse and how calling a function repeatedly avoids repeating code lines.

ELEMENTS OF A USER-DEFINED FUNCTION


To use a function in C, three important elements must be understood:

Element Purpose

Function Declaration (Prototype) Introduces the function to the compiler

Function Definition Contains the actual code of the function

Function Call Executes the function when needed

Dept of CSE, RRCE 2025-26 9


Introduction to C Programming (B25PLA105)

[Link] Definition

A function definition explains what a function does and how it works internally. It contains the actual code
that performs a specific task. In a function definition, we specify the return type, function name, parameters,
and the statements to be executed. When the function is called, these statements are executed. If the function
has a return type other than void, it sends a value back to the calling program using the return statement.
General Syntax:
return_type function_name(parameter_list) {
local variable declarations;
executable statements;
return value; // optional (depends on return type)
}
Example:
int sum (int a, int b) {
int s = a + b;
return s;
}
In this example, the function sum takes two integer values, adds them, and returns the result.

2. Function Declaration (Prototype)

A function declaration, also known as a prototype, tells the compiler about the function before it is used in the
program. It specifies the function name, return type, and the number and type of parameters, but it does not
contain the function body. This helps the compiler check for correct function usage.
General Syntax:
return_type function_name(parameter_list);
Example:
int sum (int, int);
This declaration informs the compiler that a function named sum exists which takes two integers and returns
an integer.

Dept of CSE, RRCE 2025-26 10


Introduction to C Programming (B25PLA105)

3. Function Call

A function call is used to execute the function. When a function is called, control is transferred to the function
definition, the code inside the function runs, and then control returns to the calling statement. If the function
returns a value, it can be stored in a variable.
General Syntax:
function_name(arguments);
Example:
result = sum (5, 10);
Here, the values 5 and 10 are passed to the function sum, the addition is performed, and the returned value is
stored in result.

Program 1: Function With Return Value


#include <stdio.h>
int add(int a, int b); // Function declaration

int main() {
int result = add(5, 10); // Function call
printf("Sum = %d", result);
return 0;
}

Dept of CSE, RRCE 2025-26 11


Introduction to C Programming (B25PLA105)

int add(int a, int b) { // Function definition


return a + b;
}
Output:
Sum = 15
Explanation:
• int add(int, int); tells the compiler the function exists.
• result = add(5,10); calls the function.
• The function computes and returns 15.

Program 2: Function Without Return Value (void)


#include <stdio.h>
void welcome();

int main() {
welcome();
return 0;
}
void welcome() {
printf("Welcome to Functions in C!");
}
Output:
Welcome to Functions in C!
Explanation:
Since the function does not return a value, the return type is void.

Program 3: Function With Parameters


#include <stdio.h>
void printNumber(int n);
int main() {

Dept of CSE, RRCE 2025-26 12


Introduction to C Programming (B25PLA105)

printNumber(50);
return 0;
}
void printNumber(int n) {
printf("The number is: %d", n);
}
Output:
The number is: 50
Explanation:
Parameter n receives the value 50 when the function is called. This demonstrates parameter passing.

DEFINITION OF A FUNCTION
A function definition describes what a function does and how it performs a task. It contains the actual code
that gets executed when the function is called. The function definition is where the logic of the program is
written, such as calculations, decisions, or repeated actions. A function cannot work without a proper
definition.
Components of a Function Definition
A function definition in C consists of the following components:
1. Function Return Type
The return type specifies the type of value that a function sends back to the calling function after execution.
Common return types include int, float, and char. If a function does not return any value, the return type is
specified as void. The return type helps the compiler understand what kind of result the function will produce.
Syntax
return_type function_name(parameter_list)
Example
int add(int a, int b)
{
return a + b;
}
Explanation:
Here, int is the return type, which means the function returns an integer value after adding two numbers.

Dept of CSE, RRCE 2025-26 13


Introduction to C Programming (B25PLA105)

2. Function Name
The function name is used to identify and call the function. It must follow the rules of a valid C identifier and
should clearly indicate the purpose of the function. A meaningful function name makes the program easier to
read and understand.
Syntax
return_type function_name(parameter_list)
Example
int sum(int x, int y)
{
return x + y;
}
Explanation:
The name sum clearly indicates that the function calculates the sum of two numbers.
3. Parameter List
The parameter list contains variables that receive values from the calling function. These variables are called
formal parameters. Parameters allow data to be passed into the function. If no input values are needed, the
parameter list can be empty or specified as void.
Syntax
return_type function_name(type1 param1, type2 param2)
Example
int multiply(int a, int b)
{
return a * b;
}
Explanation:
Here, a and b are parameters that receive values from the calling function and are used inside the function.
4. Function Body
The function body contains the actual executable statements that perform the task. It is enclosed within curly
braces { }. The function body may include local variable declarations, arithmetic operations, decision-making
statements, and a return statement if the function returns a value.
Syntax
{
local variable declarations;
Dept of CSE, RRCE 2025-26 14
Introduction to C Programming (B25PLA105)

executable statements;
return value;
}
Example
int square(int n)
{
int result; // local variable
result = n * n;
return result;
}
Explanation:
The variable result is local to the function. The function calculates the square of a number and returns the
result to the calling function.
General Syntax of a Function Definition
return_type function_name(parameter_list)
{
local variable declarations;
executable statements;
return value; // optional depending on return type
}
Example 1: Function That Returns a Value
#include <stdio.h>
int square(int num)
{
return num * num;
}
int main()
{
int result = square(6);
printf("Square = %d", result);
return 0;
Dept of CSE, RRCE 2025-26 15
Introduction to C Programming (B25PLA105)

}
Explanation:
The function square() receives one integer value, calculates its square, and returns the result. The returned
value is stored in the variable result and printed.
Example 2: Function Without Return Value (void)
#include <stdio.h>
void printLine()
{
printf("----------------------\n");
}
int main()
{
printLine();
printf("Function Definition Example\n");
printLine();
return 0;
}
Explanation:
The function printLine() does not return any value, so its return type is void. It is used only to perform an
action, which is printing a line.
Example 3: Function With Multiple Statements and Local Variables
#include <stdio.h>
int product(int x, int y)
{
int result;
result = x * y;
return result;
}
int main()
{
int p = product(4, 5);

Dept of CSE, RRCE 2025-26 16


Introduction to C Programming (B25PLA105)

printf("Product = %d", p);


return 0;
}
Explanation:
The function calculates the product of two numbers using a local variable and returns the result to the calling
function.
Key Points to Remember
• A semicolon (;) is not used after the function header.
• Parameters and local variables are accessible only inside the function.
• A return statement is mandatory for non-void functions.
• void functions do not return any value.
• A function executes only when it is called.

RETURN VALUES AND THEIR TYPES


A function in C may or may not return a value to the calling function. If a function is designed to return a
value, it uses the return statement to do so. While a function can receive any number of input values through
parameters, it can return only one value per call. This returned value is the output of the function, which the
calling program can use in expressions or store in a variable.
Forms of the return Statement
The return statement can be written in two ways:
1. Plain return:
2. return;
This form does not return any value. It simply stops the execution of the function and immediately transfers
control back to the calling function. It works similarly to reaching the closing brace } of the function. Plain
return is mostly used in void functions.
Example:
void check(int error)
{
if(error)
return; // exit function if error is true
printf("No error detected\n");
}

Dept of CSE, RRCE 2025-26 17


Introduction to C Programming (B25PLA105)

Here, if error is true, the function stops and control returns to the caller without executing the printf statement.
3. Return with an expression:
4. return expression;
This form returns the value of the expression to the calling function. The expression is evaluated first, and the
resulting value is passed back. This is used when the function is expected to produce some output.
Example:
int product(int x, int y)
{
return x * y; // returns the product of x and y
}
When product(4,5) is called, it returns 20 to the calling program.
Multiple return Statements
A function can contain more than one return statement. This is useful when the returned value depends on
certain conditions. Only one return statement is executed per function call, depending on which condition is
met.
Example:
int checkNumber(int n)
{
if(n < 0)
return -1; // returns -1 for negative numbers
else
return n; // returns the number itself for non-negative numbers
}
Here, the function returns different values depending on the input.
Return Type of a Function
Every function must specify a return type in its header. The return type tells the compiler what type of value
the function will return.
• By default, if a return type is not specified, C assumes it to be int.
• However, it is good programming practice to always specify the return type explicitly.

Dept of CSE, RRCE 2025-26 18


Introduction to C Programming (B25PLA105)

Examples:
int sum(int a, int b) // returns integer
float average(float x, float y) // returns float
double power(double x, int n) // returns double
char grade() // returns character
void display() // returns nothing
Automatic Type Conversion of Returned Values
When a value is returned, it is automatically converted to match the function’s return type.
Example:
int test()
{
double x = 7.98;
return x; // returns 7 (decimal part truncated)
}
Even though x is a double, the function is declared as int, so only the integer part (7) is returned. This type
conversion happens automatically.
Example of a Function with Return Value
#include <stdio.h>
int multiply(int a, int b)
{
return a * b; // returns the product
}
int main()
{
int result = multiply(4, 5); // function call
printf("Result = %d\n", result);
return 0;
}
Output:
Result = 20

Dept of CSE, RRCE 2025-26 19


Introduction to C Programming (B25PLA105)

Explanation:
• multiply receives 4 and 5 as input.
• It calculates 4*5 and returns 20 to main().
• main() stores it in result and prints it.

FUNCTION CALLS
A function call is the actual statement used to invoke a function and execute the block of code written within
that function. The function name followed by parentheses forms the call. If arguments are required by the
function, they are placed inside the parentheses; otherwise, they remain empty. When a function call is
encountered in a program, control is transferred to the called function, and once execution is completed, it
returns to the calling function.

Syntax of a Function Call

function_name(actual_parameters);

Examples:

sum(10, 20);
printline();
mul(a, b + 5);

When the Compiler Encounters a Function Call


1. The function name followed by parentheses indicates that the function must be executed.
When the compiler sees a function name followed by parentheses, it understands this as a request to run that
function.
Example:
mul(10, 5);
Here, mul is the function name, and () indicates a function call.
2. Control of execution shifts from the calling function (usually main()) to the called function.
The moment the call is made, the normal execution in main() pauses, and control jumps to the function mul().
Example:
int main()
{
mul(10, 5); // control shifts here to mul()
}
Execution stops in main() and starts in mul().
Dept of CSE, RRCE 2025-26 20
Introduction to C Programming (B25PLA105)

3. The actual parameters inside the parentheses are passed to the function’s formal parameters.
The values written during function call are assigned to variables in the function definition.
Example:
mul(10, 5); // actual parameters: 10 and 5
int mul(int x, int y) // formal parameters: x and y
So, x = 10 and y = 5.
4. Statements inside the function body are executed line by line.
Once inside the function, instructions are carried out one at a time.
Example:
int mul(int x, int y)
{
int p; // executed first
p = x * y; // executed next
return p; // executed last
}
5. If a return statement is present, a value is sent back to the calling function; otherwise, control
simply returns.
The return sends a result back. If there is no return (void function), only control returns.
Example (returns a value):
return p; // sends p back
Example (no return):
void printline()
{
printf("-----\n");
} // returns control only
6. When a value is returned, it can either be stored in a variable, used in an expression, or printed
directly.
The returned value is flexible and can be used in different ways.
Store in variable:
result = mul(10, 5);

Dept of CSE, RRCE 2025-26 21


Introduction to C Programming (B25PLA105)

Used in expression:
total = mul(10, 5) + 3;
Printed:
printf("%d", mul(10, 5));
7. After completion of the called function, control resumes from the statement following the
function call.
The program continues executing the next line in main().
Example:
int main()
{
mul(10, 5); // function call
printf("Done"); // executed after mul()
}
Output:
Done
Thus, once mul() finishes, execution resumes at printf("Done").

Using Arguments and Returned Values


1. Actual parameters can be constants, variables, or expressions.
• The values passed inside the brackets of a function call are called actual parameters.
• These can be direct numbers (constants), names of variables, or expressions that need to be evaluated
first.
• The function receives whatever value is produced by these parameters.
Examples:
mul(10, 5); // constants
mul(a, b); // variables
mul(m + 5, 10); // expression + constant

2. A function call itself can be passed as an argument to another function.


• Sometimes the output of one function can become the input for another function.
• This is called a nested function call.
Dept of CSE, RRCE 2025-26 22
Introduction to C Programming (B25PLA105)

• The inner function executes first, and its result is passed to the outer function.
Example:
mul(10, mul(a, b));
Here, mul(a, b) is executed first.
3. The type, order, and number of actual parameters must match the formal parameters.
• The function definition decides how many values it expects and what types they must be.
• If this does not match during a function call, the compiler will give an error.
Example:
int mul(int x, int y); // formal parameters: x, y
mul(10, 5); // correct
mul(10); // wrong — missing parameter
mul(10, 5, 3); // wrong — extra parameter
4. Returned values can be stored in variables.
• If a function returns a value, that value can be assigned to a variable for later use.
Example:
result = mul(a, b);
5. Returned values can be printed directly.
• The returned value can be sent to printf() without storing it.
Example:
printf("%d", mul(a, b));
6. Returned values can be used in expressions.
• A function’s return value behaves like any normal value and can be used in calculations or combined
with other operators.
Example:
z = mul(a, b) + 10;
7. A function call cannot be used on the left side of an assignment.
• Because a function call does not represent a memory location, it cannot store a value.
• Therefore, using it on the left side is incorrect.
Invalid Example:
mul(a, b) = 15;

Dept of CSE, RRCE 2025-26 23


Introduction to C Programming (B25PLA105)

8. Functions that return values can participate in arithmetic or comparison expressions.


• Since the return value is treated as a regular value, it can be compared or used in conditions.
Example:
if (mul(m, n) > total)
9. A function that does not return a value (void function) cannot be used in expressions.
• Since it returns nothing, you cannot assign it or use it in calculations.
Correct usage:
printline(); // must stand alone
10. The parentheses () of a function call have high precedence.
• This means the function call is evaluated before most other operations in an expression.
Example:
a + mul(b, c) // mul(b, c) happens first

Illustrative Example (Step-by-Step)


y = mul(10, 5);
• The program encounters the call mul(10, 5).
• Control jumps from main() to the mul() function.
• 10 is copied into parameter x, and 5 is copied into parameter y.
• The function multiplies x and y.
• The result is returned to main().
• That result is stored in the variable y.
Valid Function Calls
mul(10, 5)
mul(m, n)
mul(m + 5, 10)
mul(10, mul(a, b))

Invalid Usage
mul(a, b) = 15; // invalid

Dept of CSE, RRCE 2025-26 24


Introduction to C Programming (B25PLA105)

FUNCTION DECLARATION (FUNCTION PROTOTYPE)


Just like variables, all functions in a C program must be declared before they are used. The purpose of a
function declaration is to inform the compiler about the function’s name, the type of value it returns, and the
number and type of parameters it expects. This declaration is known as the function prototype. A prototype
acts like an introduction or preview of the function for the compiler, so when the function is called later in the
program, the compiler already knows how to handle it. Without a proper prototype, the compiler may assume
defaults and may produce errors if assumptions are wrong.
A function prototype consists of four parts:
1. Function type (return type) – specifies the kind of value returned.
2. Function name – identifies the function.
3. Parameter list – describes the data types and different arguments.
4. A terminating semicolon – marks the end of the declaration statement.
The general syntax of a function prototype is:
function-type function-name(parameter list);
This looks very similar to the function header line in the definition, except that a semicolon must be placed at
the end. For example, if a multiplication function is defined later in the program, it can be declared as:
int mul(int m, int n); // function prototype
This line informs the compiler that mul() is a function that receives two integers and returns an integer.
1. Parameters in the list must be separated by commas.
Example:
int add(int a, int b, int c);
2. Parameter names in the prototype and function definition do NOT have to match.
Prototype:
int mul(int, int);
Definition:
int mul(int x, int y) { … }
3. The data types in the prototype must exactly match those in the definition, both in number and
order.
Correct:
float area(float r);
Incorrect example:
float area(int r); // mismatched type -> error

Dept of CSE, RRCE 2025-26 25


Introduction to C Programming (B25PLA105)

4. The use of parameter names in the prototype is optional.


Both forms are acceptable:
int sum(int, int);
int sum(int a, int b);
5. If a function takes no parameters, its parameter list must be written as (void).
Example:
void display(void);
6. If a function returns an integer, the return type may be omitted, because int is assumed by
default.
Example:
sum(int a, int b); // same as int sum(int a, int b);
7. If a function does not return a value, its return type must be explicitly written as void.
Example:
void printline(void);
8. If declared parameter types do not match the function definition, the compiler will produce an
error.
Example error:
int mul(int x); // WRONG prototype for mul(int x, int y)

Global Prototypes
A global prototype is a function declaration that is written outside all functions in a program, usually placed
at the very beginning of the source code, before the main() function. Since it appears in the global declaration
section, it becomes visible to every function that follows it. This means that any function in the program can
call the declared function without errors because the compiler already knows about its return type and
parameter list.
Using global prototypes is considered good programming practice because it increases clarity and reduces the
chances of errors. When prototypes are placed in one common place, the programmer can easily refer to them
and understand the functions used in the program without searching through the code. Furthermore, having
global prototypes ensures that functions are recognized across the entire program and not limited to a specific
block or function.
Global prototypes are especially useful in large programs containing many functions, as they help maintain
consistency and prevent mismatched argument errors. In summary, a global prototype gives the function
global visibility and scope, allowing it to be called from anywhere in the program.

Dept of CSE, RRCE 2025-26 26


Introduction to C Programming (B25PLA105)

Example of a Global Prototype


#include <stdio.h>
int mul(int, int); // global prototype
int main()
{
printf("%d", mul(4, 5));
return 0;
}

int mul(int a, int b) // function definition


{
return a * b;
}
Here:
• The prototype is placed above main().
• Both main() and any other function can call mul().

Local Prototypes
A local prototype is a function declaration that is written inside a function definition, usually in the local
declaration section of main() or another function. Unlike global prototypes, a local prototype is visible only
inside the function where it is declared.
This means that if a function prototype is placed inside main(), only main() can call that function. If another
function attempts to call it without having its own local prototype, the compiler will not recognize the function
and will generate an error.
Local prototypes are used rarely, and mostly in situations where only a particular function requires knowledge
of another function’s prototype. They limit the scope of the function to the block in which it is declared. While
this may help in encapsulating functionality, it can also reduce flexibility and is not recommended for general
programs.
Because local prototypes limit the scope, they are less convenient in larger programs. Therefore, although
valid, they are not considered good programming practice unless used for specific purposes.
Example of a Local Prototype
#include <stdio.h>
int main()
{
Dept of CSE, RRCE 2025-26 27
Introduction to C Programming (B25PLA105)

int mul(int, int); // local prototype ONLY for main()

printf("%d", mul(4, 5)); // allowed


return 0;
}

int mul(int a, int b)


{
return a * b;
}
Here:
• The prototype is declared inside main().
• Only main() can call mul().
• Another function outside main() cannot call mul() unless it also declares its own prototype.
Key Differences

Feature Global Prototype Local Prototype

Placement Outside all functions Inside a function

Scope Entire program Only inside that function

Usage Preferred Rare

Flexibility High Low

Best For Large or multi-function programs Special restricted cases

Why Global Prototypes are Preferred


• easier to read and maintain
• prevent mistakes
• function available everywhere
• promotes good programming style
• improves documentation
Local prototypes limit scope and can cause confusion if used unnecessarily.
Parameters appear in three different places in a program:

Dept of CSE, RRCE 2025-26 28


Introduction to C Programming (B25PLA105)

1. Function declaration (prototype)


Example: int sum(int, int);
2. Function call
Example: sum(a, b);
3. Function definition
Example: int sum(int x, int y) { … }
• The parameters in declaration and definition are called formal parameters.
• The parameters in the function call are called actual parameters.
Actual parameters may be:
• constants → sum(10, 20)
• variables → sum(a, b)
• expressions → sum(a + b, 5)
Formal and actual parameters must match in:
• type
• order
• number
Their names do not need to match.

NO ARGUMENTS AND NO RETURN VALUES


A function with no arguments and no return value is the simplest form of a user-defined function. In this type,
the function does not depend on any external input from the calling function because it does not receive any
values. The function also does not send back any result to the caller. Instead, it completes its task entirely
inside its own body. Since it does not return a value, its return type must be written as void.
These functions are most useful when you want to perform a task that is the same every time the function is
called, regardless of input. For example, printing a message, drawing a line pattern, clearing the screen, or
displaying a welcome note. Because they do not return a value, you cannot use them in expressions or assign
them to variables. They must be called as independent statements.
Such functions help improve readability by separating tasks that are repeated often. They reduce duplication
in the program and make the code look cleaner. Although they do not exchange data with the caller, they can
still access global variables or accept input from the user inside the function if needed. Thus, these functions
offer simplicity while still performing meaningful operations.
Example
#include <stdio.h>
void printLine(void)
{
Dept of CSE, RRCE 2025-26 29
Introduction to C Programming (B25PLA105)

printf("----------------------------\n");
}
int main()
{
printLine();
printf("Welcome to C Programming!\n");
printLine();
return 0;
}
Explanation:
• printLine() has no parameters and no return.
• It prints the same output every time it is called.
• It helps avoid writing printf repeatedly.
When to Use This Type of Function
• for printing messages or output formatting
• for displaying menus
• for performing internal tasks that require no input
• when no result needs to be returned

ARGUMENTS BUT NO RETURN VALUES


There are situations where a function needs input values to perform its task, but there is no need to return a
value back. In such cases, we define the function with parameters and mark its return type as void. The
arguments allow the function to receive information necessary for processing. However, instead of returning
a value, the function may print the result or modify a global variable.
This type is useful when the function's role is to perform and display rather than perform and return. For
example, a function that calculates and prints the sum of two numbers does not need to return the result if the
output is simply displayed on the screen. These functions help separate computation from main(), and keep
the main program simple, while still utilizing the input values supplied.
Since they return no value, they cannot be used in expressions. The result cannot be stored in a variable. The
function is always called as a standalone statement. However, they are valuable when the emphasis is on
execution and presentation instead of computation and reuse of the result.
Example
#include <stdio.h>
void displaySum(int a, int b)
Dept of CSE, RRCE 2025-26 30
Introduction to C Programming (B25PLA105)

{
printf("Sum = %d\n", a + b);
}
int main()
{
displaySum(15, 25);
displaySum(7, 9);
return 0;
}
Explanation:
• Input values are passed through arguments.
• The function uses them but does not return the result.
• The function prints output directly.
When to Use This Type of Function
• when result will be printed immediately
• when returning the value is unnecessary
• for processing input without storing output

NESTING OF FUNCTIONS
Nesting of functions means calling one function from within the body of another. When nesting occurs, the
control transfers from the outer function to the inner function. After the inner function completes, the control
comes back to the outer function and continues with the next statement. Nesting is extremely helpful for
breaking down complex operations into smaller tasks.
It promotes modular programming: one function performs a smaller task (like computing a square), while
another handles a larger task (such as printing or evaluating conditions). Nesting improves reusability, because
one function can be used multiple times inside different functions. It also improves readability by making
programs more structured and well-organized.
However, nesting should be used thoughtfully. Too many nested function calls may make the program harder
to trace or debug. But when used reasonably, nesting simplifies logic and reduces code repetition.
Example
#include <stdio.h>
int square(int n)

Dept of CSE, RRCE 2025-26 31


Introduction to C Programming (B25PLA105)

{
return n * n; // inner function action
}
void displaySquare(int x)
{
int result = square(x); // nested function call
printf("Square = %d\n", result);
}
int main()
{
displaySquare(9);
displaySquare(4);
return 0;
}
Explanation:
• square() computes and returns a value.
• displaySquare() calls square() to perform the inner task.
• This division makes the program modular and clean.
Where Nesting Helps
• breaking complex logic into steps
• avoiding duplicate code
• improving readability and structure
• enabling function reuse within other functions

Dept of CSE, RRCE 2025-26 32

You might also like