Function is one of the basic elements of C language through which we can write reusable pieces of code to perform a particular task. Instead of typing the sequence of commands every time, one can write a function once and then execute it whenever necessary. Besides saving time, this approach makes our programs more modular and definitely easier to understand.
A function in C is a set of statements that are placed within a pair of curly brackets {}. It can accept inputs, process them, and produce outputs at the end of the process. This modularity assists us in simplifying issues and assuming their manageable portions. For instance, there is a situation where specific operations must be repeated in a program several times. Rather than just writing the same code over and over, one can write a function and then run it as and when needed.
Functions in C are similar in concept to subroutines or procedures in other programming languages. They assist in structuring code, which, in turn, makes it much easier to comprehend and modify. There are 2 types of functions in C: Predefined or library functions and user-defined functions. We will go through the details of these types of functions, advantages, explanations, detailed syntax and structure, and other important aspects in this blog.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
1. Predefined (Library) Functions in C
Predefined functions, which are also known as Library functions, are an indispensable tool in C programming. These functions are already coded and are stored in C libraries. They execute basic procedures which help us immensely since it frees up our time not having to write code from scratch. It will be as simple as including the correct headers to be able to use them. Well, what are some predefined functions, and how to apply them?
Common Predefined Functions and Their Usage
There are different types of functions that are classified according to the intended activities within the library. Some of the categories may include input and output operations, calculations, and character string operations, among others. Here are a few widely used library functions:
printf() and scanf(): These functions are found in the stdio. h library. printf is used for displaying output in the format that the user requires while scanf is used for entering data in the format specified by the user.
sqrt(): This function, located in the math. h library, allows the users to get the square root of any number they want.
strlen() and strcpy(): Such functions are nested in the string. h library. strlen() function gives the number of characters in the string, while the strcpy() function is used to copy one string into another.
To use these functions, it is necessary to include the following headers at the start of your program. Let’s see some examples.
Example Programs Using Predefined Functions
Example 1: Using printf() and scanf()
#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
printf("You entered: %dn", num);
return 0;
}
In this program, printf() prompts the user to enter an integer, and scanf() reads the input.
Example 2: Calculating the Square Root
#include <stdio.h>
#include <math.h>
int main() {
double num, result;
printf("Enter a number: ");
scanf("%lf", &num);
result = sqrt(num);
printf("Square root of %.2lf is %.2lfn", num, result);
return 0;
}
Here, we use sqrt() to calculate and print the square root of a given number.
2. User-Defined Functions in C
Although there are defined functions in the library they are useful, sometimes we have to write custom functions to perform the specific task. User-defined functions offer this versatility. The functions are coded by us and are developed and optimised specifically for our program.
Importance and Flexibility of User-Defined Functions
User-defined functions allow us to:
Customise functionality: we can declare functions for special tasks that would otherwise be repeated throughout our program.
Enhance modularity: It is also easier to manage and debug if the code is divided into different functions instead of one large code.
Improve code reuse: we can use the function in different parts of the program or different programs at all.
Example Programs Using User-Defined Functions
Let us examine a program that determines the area of a rectangle. For this task, we’ll define a function.
Example: Calculating the Area of a Rectangle
#include <stdio.h>
// Function declaration
int calculateArea(int, int);
int main() {
int length, width, area;
printf("Enter the length and width of the rectangle: ");
scanf("%d %d", &length, &width);
// Function call
area = calculateArea(length, width);
printf("Area of the rectangle: %dn", area);
return 0;
}
// Function definition
int calculateArea(int l, int w) {
return l * w;
}
In this program, we declare the calculateArea function at the beginning. The main function reads the rectangle’s dimensions from the user, calls the calculateArea function, and prints the result. The calculateArea function takes two integers as arguments and returns their product.
Advantages of Using Functions in C
1. Avoidance of Code Repetition
Among the most important purposes of the function is to eliminate copy-paste or rewriting of the same code multiple times. Repeating the same lines of code hinders efficient coding in several ways: A redundancy of code is error-prone and hard to manage during maintenance. When using functions, we write the code just once, and then we call it, which saves time.
2. Simplification of Program Tracking and Management
It is easier to track a program if it is divided into functions because it reduces the complexity of the program. Every function has its designated role, making it possible for us to work on one section of the program at a time.
3. Facilitation of Code Reuse and Encapsulation
Functions promote code reuse. By defining a function, we can use it whenever it is needed throughout the program or even in another program. This practice also boosts encapsulation in which functions’ inner workings are masked to the rest of the code.
4. Enhancement of Program Readability and Maintainability
It is important to note that functions help to make programs more readable. These are the naming conventions that make a function explain its purpose while at the same time making the code self-explanatory. This also makes code easier to manage since we can easily navigate to specific functions if we need to edit them, sacrificing other parts of the program.
5. Improved Collaboration among Developers
Functions facilitate coordination in a team setup. The modular approach allows team members to develop the different functions concurrently and then assemble them into a coherent program. Such division of work enhances efficiency in the development of the various aspects of the program most effectively.
Detailed Syntax and Structure of Functions in C
Understanding the syntax and structure of functions is crucial for effective programming in C. Let’s break down the components of a function:
Function Syntax
In C, the syntax of a function can be defined by using return type, function name, parameters, and body. Here’s a general template:
return_type function_name(parameter_list) {
// Function body
}
Return Type: Declares the type of a value that the given function will return. If the function does not have any value to return, then we make use of void.
Function Name: A name for the function, which has to be unique. It should contain a description of what the function does or, perhaps, the general purpose of the function.
Parameter List: Holds the parameters (inputs) the function can accept. If there are no parameters, then it could be left blank.
Function Body: Surrounded by curly braces {}, this part encompasses the statements that proscribe the action of the function.
Function Declaration
A function is usually defined before calling it. The declaration informs the compiler about the function’s name, the type of data that is returned, and the type of data that is passed to the function through its parameters. Often, it is placed at the start of the program or the beginning of a header file. Here’s an example:
int add(int, int);
This declaration informs the compiler that there is a function named add that takes two integer arguments and returns an integer.
Function Definition
The definition of a function also involves a declaration and the body of the function. This is where we come up with the actual code that the function will perform. For example:
int add(int a, int b) {
return a + b;
}
In this example, add is a function that accepts two integers and then returns the sum of the given two integers.
Function Call
To perform a function, it is called from another part of the program, possibly main(). A function call involves the name of the function that is being called and the parameters passed to the function. Here’s an example:
int result = add(5, 3);
In this call, we have passed 5 and 3 to the function add, which gives out 8, and this is stored in the variable result.
Example Program: Adding Two Numbers
Let’s examine a comprehensive example that shows the syntax and structure of C functions:
#include <stdio.h>
// Function declaration
int add(int, int);
int main() {
int num1, num2, sum;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
// Function call
sum = add(num1, num2);
printf("Sum: %dn", sum);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
We define the add function at the start of this program. After reading two numbers from the user, the main function performs the add function and displays the outcome. After receiving two integers as inputs, the add function adds them and returns the sum.
Different Categories of Functions Based on Parameters and Return Values
Functions in C can be classified based on whether or not they return values and take parameters. Let us examine these classifications.
Functions with Arguments and Return Values
These functions accept parameters and return a result. They are adaptable and may be utilised in many scenarios. For example:
int multiply(int a, int b) {
return a * b;
}
This function takes two integers, multiplies them, and returns the result.
Functions with Arguments but Without Return Values
These functions take parameters but do not return a value. They are useful when we need to act but do not need to return a result. For example:
void printSum(int a, int b) {
int sum = a + b;
printf("Sum: %dn", sum);
}
This function takes two integers, calculates their sum, and prints the result.
Functions Without Arguments but With Return Values
These functions return a value and do not take any parameters. When a function performs an action and returns a value, it is useful. For example:
int getRandomNumber() {
return rand();
}
This function returns a random number.
Functions Without Arguments and Without Return Values
These functions do not take parameters or return a value. They are handy for executing activities that do not need inputs or outputs. For example:
void printMessage() {
printf("Hello, World!n");
}
This function prints a message to the screen.
Example Programs for Each Category
To better understand these categories, let’s look at some example programs.
Example: Function with Arguments and Return Values
#include <stdio.h>
// Function declaration
int multiply(int, int);
int main() {
int a, b, result;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
// Function call
result = multiply(a, b);
printf("Product: %dn", result);
return 0;
}
// Function definition
int multiply(int x, int y) {
return x * y;
}
This program reads two integers, calls the multiply function, and prints the product.
Example: Function with Arguments but Without Return Values
#include <stdio.h>
// Function declaration
void printSum(int, int);
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
// Function call
printSum(a, b);
return 0;
}
// Function definition
void printSum(int x, int y) {
int sum = x + y;
printf("Sum: %dn", sum);
}
This program reads two integers, calls the printSum function, and prints the sum.
Example: Function Without Arguments but With Return Values
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Function declaration
int getRandomNumber();
int main() {
srand(time(0)); // Seed the random number generator
int number = getRandomNumber();
printf("Random number: %dn", number);
return 0;
}
// Function definition
int getRandomNumber() {
return rand();
}
This program generates and prints a random number.
Example: Function Without Arguments and Without Return Values
#include <stdio.h>
// Function declaration
void printMessage();
int main() {
// Function call
printMessage();
return 0;
}
// Function definition
void printMessage() {
printf("Hello, World!n");
}
This program calls the printMessage function, which prints a message to the screen.
Passing Parameters to Functions in C
Passing parameters to functions is crucial for making our code flexible and reusable. We can pass data to functions in two primary ways: by value and by reference. Understanding these methods helps us write more efficient and effective code.
Pass by Value
When we pass parameters by value, the function receives a copy of the actual data. Changes made to the parameter inside the function do not affect the original value. This method is straightforward and ensures that the original data remains unchanged.
Example: Pass by Value
Let’s look at an example to understand this better.
#include <stdio.h>
// Function declaration
void swapByValue(int, int);
int main() {
int a = 10, b = 20;
printf("Before swap: a = %d, b = %dn", a, b);
// Function call
swapByValue(a, b);
printf("After swap (by value): a = %d, b = %dn", a, b);
return 0;
}
// Function definition
void swapByValue(int x, int y) {
int temp = x;
x = y;
y = temp;
}
In this example, the values of a and b are not swapped in the main function because only copies of the values are passed to the swapByValue function.
Pass by Reference
When we pass parameters by reference, the function receives a reference to the actual data. This allows the function to modify the original data directly. This method is useful when we need the function to update the data.
Example: Pass by Reference
Here’s an example of passing parameters by reference.
#include <stdio.h>
// Function declaration
void swapByReference(int *, int *);
int main() {
int a = 10, b = 20;
printf("Before swap: a = %d, b = %dn", a, b);
// Function call
swapByReference(&a, &b);
printf("After swap (by reference): a = %d, b = %dn", a, b);
return 0;
}
// Function definition
void swapByReference(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
In this example, the values of a and b are swapped in the main function because the swapByReference function modifies the actual data.
Additional Concepts Related to Functions in C
Understanding more advanced concepts like recursive functions and inline functions can further enhance our programming skills. Let’s explore these concepts.
Recursive Functions and Their Implementation
A recursive function is a function that calls itself. This approach can solve problems that can be broken down into smaller, similar sub-problems. Recursion can simplify complex problems, making them easier to solve.
Example: Calculating Factorial Using Recursion
Let’s see how we can use a recursive function to calculate the factorial of a number.
#include <stdio.h>
// Function declaration
int factorial(int);
int main() {
int num = 5;
printf("Factorial of %d is %dn", num, factorial(num));
return 0;
}
// Function definition
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
In this example, the factorial function calls itself to calculate the factorial of the number 5.
Inline Functions and Their Benefits
Inline functions are small functions that are expanded in line when they are called. This means the compiler replaces the function call with the actual code of the function. Inline functions can improve performance by eliminating the overhead of a function call, but they should be used sparingly to avoid code bloat.
Example: Using Inline Functions
Here’s an example of defining an inline function.
#include <stdio.h>
// Inline function declaration
inline int square(int x) {
return x * x;
}
int main() {
int num = 4;
printf("Square of %d is %dn", num, square(num));
return 0;
}
In this example, the square function is expanded in line, making the code more efficient.
In this blog, we looked at the various types of functions in C language programming and their uses. In the beginning, predefined functions helped us to avoid wasting much time creating them individually. Next, we were introduced to user-defined functions, which give flexibility and modularity to the program and allow one to solve a certain problem in the best way by writing a unique program for it. We also included a discussion on how and why values are passed to and from functions, including value parameters and reference parameters.
Moreover, we discussed more complex topics such as recursive functions and inline functions, which, if mastered, can enable greater coding possibilities. Once we understand and learn these concepts, we are in a position to write good, efficient, and clear code that is easy to maintain. In functions definition in C language, the efficiency is given by dividing the tasks into smaller ones, leaving the code cleaner and more efficient.
FAQs
What are the main differences between predefined and user-defined functions in C?
Predefined functions are those functions that are supplied by the C standard library and are easily accessible like printf() and scanf(). User-defined functions are developed by programmers to achieve a particular function, which is more flexible when compared to pre-defined functions.
How do formal parameters differ from actual parameters in function calls?
The formal parameters refer to the variables declared in the function header and definition. Actual parameters are those values that are provided in the function call statement. For instance, in int add(int a, int b) – a and b are the examples of the formal parameters. In the case of calling add(5, 3), 5 and 3 are actual parameters.
Can a C function return multiple values? If not, how can this be achieved?
A C function cannot directly return multiple values. But this can be done with the help of pointers, structures, or arrays only to some extent. For instance, we can pass pointers as parameters in a function to alter several values.
What are the advantages of using inline functions over regular functions?
Inline functions are useful for optimising code since a function call process is not needed. The compiler eliminates the function call and replaces it with the code of the function, which is beneficial for performance. But they should be used carefully as they lead to the creation of large amounts of code.
How do recursive functions work, and what are some common use cases?
Recursive functions invoke themselves to handle smaller parts of the same problem. They can be applied to problems involving factorials, Fibonacci numbers, and graph and tree traversal. By decomposing problems into sub-problems, recursion makes the code easier to write for complicated problems.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.