View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Master User Defined Function in C: Practical Examples & Best Practices

Updated on 07/04/20255,831 Views

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.

What is a 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.

Syntax of a User-Defined Function in C

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);

  • return_type: The type of value the function returns, such as int, float, void (if no return value), etc.
  • function_name: The name of the function.
  • parameter_list: A comma-separated list of parameters (or arguments) that the function accepts.

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);

Top 7 Examples of User Defined Function in C

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.

1. Simple Function with No Return Value (Void Function)

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:

  1. void greet(): This is a void function, meaning it does not return a value. It takes no parameters.
  2. Inside the function, we print a welcome message.
  3. greet() is called in the main() function, which outputs the message.

Output:

Hello, Welcome to C programming!

Must Read: 29 C Programming Projects in 2025 for All Levels [Source Code Included]

2. Function with a Return Value

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:

  1. int add(int a, int b): This function adds two integers a and b and returns their sum as an integer.
  2. We call add(10, 20) in main(), which calculates the sum and stores it in the variable result.
  3. The result is then printed.

Output:

The sum of 10 and 20 is: 30

3. Function with Multiple Parameters

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:

  1. float calculateArea(float length, float width): This function calculates the area of a rectangle using the formula Area = length * width.
  2. The function takes two float parameters (length and width) and returns the calculated area.
  3. The result is stored in the variable area and printed in main().

Output:

The area of the rectangle is: 17.60

Also Explore: What are Data Structures in C & How to Use Them?

4. Function Returning a Value Based on Conditions

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:

  1. const char* checkNumber(int num): This function takes an integer and returns a string that describes whether the number is positive, negative, or zero.
  2. The function uses if-else conditions to determine the status of the number.
  3. The result is printed in main().

Output:

The number -7 is: Negative

Check out the Executive Diploma in Data Science & AI with IIIT-B!

5. Function to Find the Maximum of Two Numbers

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:

  1. int findMax(int a, int b): This function compares two integers and returns the larger one.
  2. We call findMax(x, y) in main(), where x = 15 and y = 20, and print the maximum.

Output:

The maximum of 15 and 20 is: 20

Pursue DBA in Digital Leadership from Golden Gate University, San Francisco!

6. Function to Count Vowels in a String

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:

  1. int countVowels(const char* str): This function counts the vowels in a string.
  2. It uses a while loop to check each character of the string and increments count when a vowel is found.
  3. The result is printed in main().

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:

  1. int factorial(int n): This function calculates the factorial of a number using recursion. The base case is when n is 0 or 1.
  2. The function keeps calling itself with n-1 until the base case is met.
  3. The result is printed in main().

Output:

The factorial of 5 is: 120

Best Practices for Using User Defined Function in C

To get the most out of user defined function in C, it’s essential to follow some best practices:

  1. Modularity: Break your code into smaller, logically organized functions. Each function should perform a single task to improve readability and reusability.
  2. Meaningful Names: Give your functions and parameters descriptive names that explain their purpose. This helps in making the code more understandable.
  3. Avoid Global Variables: Whenever possible, avoid using global variables in your functions. Use function parameters and return values instead.
  4. Document Functions: Always comment your functions with clear documentation. This helps you and others understand the purpose of each function.
  5. Use Return Values: Functions should return values when appropriate, as they allow better flexibility and can be easily used in expressions or assignments.

Errors to Avoid When Using User Defined Function in C

While user defined function in C provide many benefits, there are some common mistakes you should avoid:

  1. Not Returning a Value When Expected: If a function is supposed to return a value, ensure that the return type is properly defined and a return statement is used in the function.
  2. Incorrect Function Signature: Make sure the return type and parameters in the function definition match the prototype declaration. Mismatches can lead to errors.
  3. Calling a Function Before Declaration: In C, you must declare functions before calling them, either by using a function prototype or defining the function above the main program.
  4. Ignoring Parameter Passing Mechanisms: Pay attention to how arguments are passed—by value or by reference. Misunderstanding this can lead to bugs where the function behaves unexpectedly.
  5. Not Handling Edge Cases: Ensure that your functions handle edge cases, like zero values, negative numbers, or empty inputs where applicable.

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.

Conclusion

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.

FAQs on User defined function in C

1. What is the main advantage of using user defined function in C ?

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.

2. Can a user defined function in C return multiple values?

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:

  • Pointers: Use pointers to modify multiple variables within the function.
  • Structures: You can return a structure containing multiple values, each representing different results.
  • Arrays: If you're dealing with a collection of values, you can return an array (by passing it to the function or using dynamic memory allocation).

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;
}

3. What is the difference between a function declaration and function definition in C?

  • Function Declaration: Also known as a function prototype, it provides the function signature, specifying the function's return type, name, and parameters. It informs the compiler about the function’s existence before it's used in the program. Example:
  • int add(int a, int b);
  • Function Definition: This is where the function’s logic is written. It provides the actual code that gets executed when the function is called. Example:
  • int add(int a, int b) {
  • return a + b;
  • }

4. Can I call a user-defined function before its declaration in C?

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:

  • Declaring the function before calling it (using a function prototype).
  • Defining the function above the main() function, so it’s available when called.

5. What happens if I forget to return a value from a function that has a non-void return type?

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!
}

6. Can we use user defined function in C without parameters?

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;
}

7. How does passing by value work in user defined function in C ?

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

8. What is the role of the void return type in C functions?

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.

9. Can we call a user defined function in C from another function?

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!

10. Can I use global variables inside a user-defined function in C?

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

11. How do recursive functions work in C, and can they be used in user-defined functions?

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

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

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.