User Defined Functions in C
Learn via video course

Overview
A function is a block of code that can be used to perform a specific action. C allows programmers to write their own functions, also known as user-defined functions. A user-defined function has three main components that are function declarations, function definition and function call. Further functions can be called by call by value or call by reference. Functions need to be written once and can be called as many times as required inside the program, which increases reusability in code and makes code more readable and easy to test, debug, and maintain the code.
Scope of article
- This article explains what user-defined functions are and how they can be used in programs.
- This article discusses how a user-defined function can be declared and defined in C programs.
- How user-defined functions are called in C programs is also discussed in this article.
- This article does not discuss how all different data structures, such as arrays are passed and handled in functions.
Introduction
Let us look at an example to calculate factorial of a number '5' in C.
Output
Now every time we want to calculate the factorial of a different number, we have to rewrite this complete logic again. Instead, we can write a general logic and use this logic every time we need to calculate the factorial. This way using functions helps in avoiding code duplicacy in the program because instead of calculating factorial several times for different numbers, we can create a function and use it anywhere in the code.
A function is a block of code that can be used to perform a specific action. C allows users to create their own functions called user-defined functions. A user-defined function can perform specific actions defined by users based on given inputs and deliver the required output.
Function divides our program into several independent sub-tasks, making our code easier to test and debug than one extensive program. The function also helps us avoid duplication of efforts in our code as we don't have to write the same code again, reducing the time to write code as explained in the above example.
Elements of User-defined Function in C
Functions in the C language have three parts. Let us discuss each of them in detail.
Function declaration
A function declaration is simply a prototype of our function. Function declaration contains function name, return type, and parameters but does not contain the body of the function. Function declaration gives information to the compiler about the user-defined function that may be used in the later part of the code.
Syntax of function declaration
A function declaration has three main components: return type, function name, and parameters. The function name is used to identify the function uniquely in code. Function parameters are included in the declaration to identify the number and types of inputs that the function accepts.
It is not compulsory to mention parameter name in declaration hence we can also use
For example, we have a function with the name getRectangleArea to calculate the area of a rectangle that takes two integer inputs i.e. length and breadth, and returns an integer area as an output.
Declaration of such a function will be
Let us understand each component of a function declaration in detail:
- Return type: The type of data returned from the function is called return type. A function may not return any output, in that case, we use void as the return type. In function declaration return type is mentioned before the name of the function.
- Function name: Function name is a unique name that can be used to identify our function in the program. Function names are used to create function calls, which is why they are unique identifiers for compilers. A valid function name in C can contain letters, underscore, and digits; the first letter must not be a digit.
For example,
- Parameter list: Parameters required by the function are also defined inside the declaration to tell the compiler number of arguments required by the function along with their data types.
- Semicolon: Semicolon indicates the termination of a function declaration.
Note: Function declaration is not required if the function is defined before it is called in the code.
Function Definition
Function definition contains the actual block of code that is executed once the function is called. A function definition has four components:
- Return type
- Function name
- Function parameters
- Body of function
We have discussed the first three components of a function declaration.
Function body contains a collection of instructions that define what a function does. If the function returns any value, we use the keyword return to return the value from the function. For example, return (5*10); returns value 50 of integer data type.
Syntax of function definition
We can also give default values to function parameters that are assigned to the parameter if no argument is passed. For example,
If getRectangleArea() is called, default values will be assigned to function parameters and 50 will be returned as function output. Here return is used to terminate the function call. After, the return statement control is transferred to the calling function in the program.
Calling User-defined Functions
To transfer the control to a user-defined function, we need to call the function. A function can be called using a function name followed by round brackets. We can pass arguments to function inside brackets, if any.
As shown in the figure, when a function call is made (sum(10,5) in this case) the control of the program shift from the calling function (main()) to the called function (sum()). The control reaches back to the calling function when the called function terminates. If the called function has any return value that it gets returned and can be accessed in the calling function like in the above figure, the sum of two integers is stored in a variable ans in function main().
Syntax for function call
A function call includes two things that are function name and function arguments. The function name is used to identify the function getting called and arguments are passed inside parentheses that act as input for the called function. Arguments must be passed in the exact order in which they are present in the function declaration.
Creating a Function Call
To call a function and calculate its output, we need to create a function call. Whenever a function is called, control of the program is transferred to called function, and the function body of the called function is executed. To create a function call, we use function name followed by values of argument enclosed inside round brackets in the exact order defined in the function declaration. For example, to call a function with name getReactangleArea accepting two arguments length and breadth, the syntax will be
here getReactangleArea(l, b) is function call and the output of the function is returned in variable area.
There are two types of function calls.
1. Call by value
In call by value function, argument values are copied to function parameters and we cannot modify the actual value of parameters. In this approach, copies of the variables are created of variables passed to function arguments. These copies remain in the stack segment of memory and are overwritten when the program leaves the called function scope.
Output
Here, the value of variable a does not change because when a is passed to the function increment the actual reference of the variable is not passed instead, a copy of variable a is created and passed to the function, and its value is increased by one. This is the reason why the value of the actual variable a inside main() does not change.
2. Call by reference
In this approach, the address of arguments is passed to function parameters, and any change performed on arguments persists outside the function scope.
Output
In this example, instead of passing a copy of the variable, we have passed the reference of variable a to function. Inside function increment, the value stored in the address where variable a is stored in memory increment by 1 and the change persists after the program has left called function scope. This approach of creating a function call is called call by reference.
Return Statement
We can consider the return statement as the final stage of a pizza-making machine, where we have inserted all the ingredients to make a pizza into the machine from one side. After the pizza is processed, we return the final baked pizza (output) from the other end of the machine.
Return statement is used to return a value from the function and terminates the execution of a function and returns the control to the calling function. Execution resumes immediately from the point following the function call.
Note: The data type of the value returned from the function must match the data type defined in the function declaration and definition.
Syntax of return statement
If present, the value of an expression is evaluated and then converted to the return type returned by the function. If the function has no return type void then a return statement is not required inside the function definition.
If no return statement is present in the function body, control of the program reaches to calling function after the last line is executed. It is good practice to mention the return statement in the function and if a function has no return type C compiler assumes a default value of int.
C compiler may issue a warning when an expression is present after the return statement to indicate code after the return statement is unreachable, the function has code that can never run.
Example
Output
Here, we have typecasted the denominator to double to make sure the compiler does not perform integer division. Notice we have also not stored the division output in a variable of type double instead, we have directly returned it if any compiler has typecasted the output to double for us.
return; can be used if function has return type void.
For example,
Passing Arguments to a Function
Data can be passed to functions in the form of arguments. For example, the function
l, b are two function arguments passed during the function call. The parameters length and breadth in the called function definition are used to access these values passed inside the scope of our function.
The data type of function argument and actual parameters passed during the function call must match otherwise compiler throws an error. Also, parameters must be passed to the function during the function call in the exact order as they are defined in the function declaration.
A function can also be called without any arguments and a C function has no limit to the number of arguments that can be passed to a user-defined function.
Example of User-defined function
Here is an example to calculate area of a Rectangle. We have created user-defined function getRectangleArea() to perform this task.
Output
Types of User-defined Functions in C
Now that we understand how user-defined functions are written in C, let us understand four different approaches which can be used to define and use a function in our code.
1. Function with No Return Value and without Argument
Output
Here, we have used the function generateFibo() that takes no input and output but generates the first ten Fibonacci numbers and stores them in the global array fibo. This is an example of a function that takes no input and returns no value. Also, observe that our function main in code is also of this type because the main is neither taking any argument nor returning any.
2. Function with No Return Value and with Arguments
Output
In this case, our function swap takes two arguments but doesn’t return any value. Notice because the arguments are integer pointers, we pass the reference of variables in the main function instead of passing values. Also, because the function call is by reference, changes persist after the program leaves called function scope, as we can see from the program's output.
3. Function with a Return Value and without Any Argument
Output
In the example, the called function circleArea() takes no argument because no values are passed to the function when called inside the calling function main(). To calculate the area of the circle, the radius is taken from the user inside the function, and after the area is calculated the value is returned from the function. Similarly, observe how the function main in the program also returns a value 0 and takes no input.
4. Function with a Return Value and with an Argument
Output
Here, we have created a function isPrime that takes an integer number as an input and checks whether the number is prime or not, the return value of the function is of the type int and if a returned value from the function is not 0 it indicates the number is prime otherwise input number is not a prime number.
What is the Best Approach?
The answer depends on the use of the function in the program. For example, it is a better approach to use a function that takes arguments as pointers but does not return a value when we need a function that performs an operation similar to swapping two numbers as shown above because we are changing the values of the function argument but, it will not be useful in cases where we need to calculate the area of a circle.
There may be cases where one approach fits the use case better than the other or maybe all approaches are equally optimal hence, the approach depends on the programmer and the requirements of the program.
Advantages of Using Functions
- Functions help us to avoid duplication of code in the program. Not only does this reduce the time to write code but it also improves code readability.
- Functions allow us to use the divide and conquer strategy in our code. It is hard to write a very large single code inside the main function and test and debug easily. Functions help us to divide our one task into several small sub-task and hence reducing the overall complexity.
- Functions help us to hide implementation details in the program, for example, C has header file math.h, which allows us to use functions like pow, sqrt, etc. without ever knowing how they are implemented.
- Function developed in one program can be used in another with little to no modifications, reducing development time.
Conclusion
- User-defined functions are a block of code written by the user to perform a specific action.
- A user-defined function has a return type, a function name, parameters, and the body of the function.
- Function can be called using the unique name of the function followed by function parameters passed inside round brackets ().
- Use of functions in code reduces program complexity. It makes testing and debugging easy and increases code reusability as we write a logic once and use it across the program several times.