For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
When it comes to mastering C programming, one of the most powerful tools in a programmer's arsenal is the ability to use user defined functions in C. These functions are key to writing clean, efficient, and modular code. By defining your own function in C, you can break down complex tasks into smaller, more manageable pieces.
In this detailed guide, we will walk you through the fundamentals of user defined function in C , including the syntax, how to define and use them, and the benefits they bring to your coding workflow. We’ll also dive into practical examples with step-by-step explanations to help you solidify your understanding. Additionally, we’ll include a Best Practices section and Errors to Avoid when using user defined function in C.
A user defined function in C is a function created by the programmer to perform a specific task. Unlike standard functions such as printf() or scanf(), which are predefined in C's standard library, a user defined function in C allows you to write your own code and call it whenever needed.
If you have ever utilized a static function, then it can be a bit easy to understand user defined function in C. This is particularly useful when you want to perform a task multiple times in different places of your program without repeating the same code each time.
The primary goal of using user defined function in C is to make your code more readable, reusable, and maintainable. By breaking down tasks into functions, you can isolate logic, making your code easier to manage and debug. That’s why, all software development courses use this topic as a building foundation.
Before we dive into examples, let's first understand the basic syntax of a user defined function in C.
Function Declaration (Prototype)
The function prototype is where you define the function's signature: its return type, name, and parameters.
return_type function_name(parameter_list);
Must Explore: Introduction to C Tutorial
Function Definition
After declaring a function, you need to define it with the logic that it will perform.
return_type function_name(parameter_list) {
// Function body (code to be executed)
}
Function Call
Once a function is defined, you can call it anywhere in your program using the function name and passing the appropriate arguments.
function_name(arguments);
Now that you understand the basic syntax, let’s go through 7 examples of user defined function in C. These examples will help you understand different ways to use functions in C for various tasks. Each example will be explained step by step, with clear outputs.
In this example, we will create a simple user defined function in C that doesn't return any value and simply prints a message to the console.
#include <stdio.h>
void greet() {
printf("Hello, Welcome to C programming!\n");
}
int main() {
greet(); // Function call
return 0;
}
Explanation:
Output:
Hello, Welcome to C programming!
Must Read: 29 C Programming Projects in 2025 for All Levels [Source Code Included]
Next, we define a user defined function in C that takes two integers as arguments and returns their sum.
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(10, 20); // Calling the function and storing the result
printf("The sum of 10 and 20 is: %d\n", result);
return 0;
}
Explanation:
Output:
The sum of 10 and 20 is: 30
In this example, we execute a user defined function in C that calculates the area of a rectangle given its length and width.
#include <stdio.h>
float calculateArea(float length, float width) {
return length * width; // Area of the rectangle
}
int main() {
float length = 5.5;
float width = 3.2;
float area = calculateArea(length, width); // Function call
printf("The area of the rectangle is: %.2f\n", area);
return 0;
}
Explanation:
Output:
The area of the rectangle is: 17.60
Also Explore: What are Data Structures in C & How to Use Them?
Here, we execute a user defined function in C that checks if a number is positive, negative, or zero.
#include <stdio.h>
const char* checkNumber(int num) {
if (num > 0) {
return "Positive";
} else if (num < 0) {
return "Negative";
} else {
return "Zero";
}
}
int main() {
int num = -7;
printf("The number %d is: %s\n", num, checkNumber(num)); // Function call
return 0;
}
Explanation:
Output:
The number -7 is: Negative
Check out the Executive Diploma in Data Science & AI with IIIT-B!
This user defined function in C returns the larger of two integers.
#include <stdio.h>
int findMax(int a, int b) {
if (a > b) {
return a; // If a is greater, return a
} else {
return b; // Otherwise, return b
}
}
int main() {
int x = 15, y = 20;
printf("The maximum of %d and %d is: %d\n", x, y, findMax(x, y)); // Function call
return 0;
}
Explanation:
Output:
The maximum of 15 and 20 is: 20
Pursue DBA in Digital Leadership from Golden Gate University, San Francisco!
This function counts the number of vowels in a given string.
#include <stdio.h>
int countVowels(const char* str) {
int count = 0;
while (*str != '\0') { // Loop through each character
if (*str == 'a' || *str == 'e' || *str == 'i' || *str == 'o' || *str == 'u' ||
*str == 'A' || *str == 'E' || *str == 'I' || *str == 'O' || *str == 'U') {
count++; // Increment if the character is a vowel
}
str++; // Move to next character
}
return count;
}
int main() {
char text[] = "Hello, World!";
int vowels = countVowels(text); // Function call
printf("The number of vowels in the string is: %d\n", vowels);
return 0;
}
Explanation:
Output:
The number of vowels in the string is: 3
7. Recursive Function to Calculate Factorial
To easily understand this example, you should first learn the basics of factorial in C. This example demonstrates how to use recursion to calculate the factorial of a number.
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive case
}
int main() {
int num = 5;
printf("The factorial of %d is: %d\n", num, factorial(num)); // Function call
return 0;
}
Explanation:
Output:
The factorial of 5 is: 120
To get the most out of user defined function in C, it’s essential to follow some best practices:
While user defined function in C provide many benefits, there are some common mistakes you should avoid:
Once, you understand the user defined functions in C, you’re ready to tackle the complexities of programming world, and build a strong foundation for high-end courses, like data analytics, machine learning and more.
As we've seen in the examples above, user defined function in C are a powerful tool for improving the readability, modularity, and reusability of your code. By defining your own functions, you break your program into smaller, manageable parts that can be reused throughout your code, leading to better structure and efficiency. Following the best practices and avoiding common errors will help you harness the full potential of user defined function in C and write more efficient, maintainable programs.
The main advantage of using user defined function in C is modularity. By breaking a program into smaller functions, you can isolate complex tasks into manageable units. This leads to cleaner, more organized, and reusable code. User-defined functions also enhance code readability, debugging, and maintainability by allowing you to work with specific functionalities independently.
No, a user defined function in C cannot directly return multiple values. However, you can return multiple values indirectly by using one of the following methods:
Example (returning multiple values via a structure):
#include <stdio.h>
struct Result {
int sum;
int product;
};
struct Result calculate(int a, int b) {
struct Result res;
res.sum = a + b;
res.product = a * b;
return res;
}
int main() {
struct Result res = calculate(5, 3);
printf("Sum: %d, Product: %d\n", res.sum, res.product);
return 0;
}
No, in C, you cannot call a user-defined function before its declaration unless you provide the compiler with prior knowledge of its signature. You can do this by either:
If a user defined function in C is declared to return a value (non-void return type) but doesn’t have a return statement, it will lead to undefined behavior. This can cause issues such as garbage values or crashes, making debugging difficult. Always ensure that a return value is provided if the function's return type isn't void.
Example of incorrect function:
int add(int a, int b) {
// Missing return statement!
}
Yes, you can create user defined function in C that do not take any parameters. This is commonly done when the function does not require any external data to perform its task. Such functions can access only global variables or predefined data.
Example:
#include <stdio.h>
void greet() {
printf("Hello, World!\n");
}
int main() {
greet(); // No parameters are passed
return 0;
}
In C, when you pass arguments to a user-defined function, they are passed by value by default. This means that a copy of the argument is passed to the function, and any modifications made within the function do not affect the original variable outside the function.
Example:
#include <stdio.h>
void modifyValue(int a) {
a = 20; // Modifies only the copy of 'a' inside the function
}
int main() {
int num = 10;
modifyValue(num); // Passing by value
printf("Value after function call: %d\n", num); // num remains unchanged
return 0;
}
Output:
Value after function call: 10
The void return type in user defined function in C indicates that the function does not return any value. These types of functions are typically used when a task is performed but there’s no need to send a result back to the caller.
Example of a void function:
#include <stdio.h>
void printMessage() {
printf("This function does not return anything.\n");
}
int main() {
printMessage();
return 0;
}
Output:
This function does not return anything.
Yes, you can call a user defined function in C from any other function, including other user-defined functions. This is a common practice to structure code in a modular fashion. You can call a function in main(), or from within another user-defined function, to reuse code and keep your program efficient.
Example:
#include <stdio.h>
void greet() {
printf("Hello from the greet function!\n");
}
void callGreet() {
greet(); // Calling the greet function from another function
}
int main() {
callGreet(); // Main calling callGreet, which in turn calls greet
return 0;
}
Output:
Hello from the greet function!
Yes, user defined function in C can access global variables declared outside of any function, including main(). However, this is generally discouraged in large programs because it reduces code modularity and increases the risk of unintended side effects. It's recommended to pass values to functions via parameters instead.
Example using a global variable:
#include <stdio.h>
int globalVar = 5; // Global variable
void printGlobal() {
printf("Global variable value: %d\n", globalVar); // Accessing global variable inside function
}
int main() {
printGlobal();
return 0;
}
Output:
Global variable value: 5
Yes, recursive functions can be used in user defined function in C. A recursive function is a function that calls itself in order to solve smaller instances of the same problem. The function should always have a base case to avoid infinite recursion and stack overflow errors.
Example (factorial function):
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive case
}
int main() {
int result = factorial(5); // Calling the recursive function
printf("Factorial of 5 is: %d\n", result);
return 0;
}
Output:
Factorial of 5 is: 120
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.