User-Defined Functions in C Programming
User-Defined Functions in C Programming
MODULE - 04
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:
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:
Library Functions printf(), scanf(), sqrt(), Already written and provided by the C
strlen() library
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().
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().
Advantage Meaning
return 0;
}
If we need 100 “Hello”, we must repeat the line 100 times — not practical.
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().
void message() {
printf("Functions make programs easy!\n");
}
int main() {
line();
message();
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;
}
void printline() {
for(int i = 1; i <= 39; i++)
printf("-");
}
Output
---------------------------------------
This illustrates the use of C functions
---------------------------------------
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.
Element Purpose
[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.
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.
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.
int main() {
int result = add(5, 10); // Function call
printf("Sum = %d", result);
return 0;
}
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.
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.
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);
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.
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
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.
function_name(actual_parameters);
Examples:
sum(10, 20);
printline();
mul(a, b + 5);
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);
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").
• 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;
Invalid Usage
mul(a, b) = 15; // invalid
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.
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)
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
{
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)
{
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