Tutorial Playlist
User defined functions in C allow programmers to create custom code blocks for performing specific actions. They consist of function declarations, definitions, and calls, providing a blueprint for the function, while definitions contain the actual code. User-defined functions simplify testing, debugging, and code maintenance by encapsulating logic into modular blocks.
In order to further understand the user-defined functions in C, let’s understand its advantages -
There are four types of user-defined functions in C. Let’s study what they are with some examples -
This type of function does not return any value and does not require any arguments.
#include <stdio.h> |
Output:
Hello, world! |
In this example, the greet function is defined without a return type (void) and any arguments. It simply prints "Hello, world!" to the console. The greet function is called from the main function, resulting in the greeting being displayed.
This type of function does not return any value but requires one or more arguments.
#include <stdio.h> |
Output:
Sum: 8 |
In this example, the addNumbers function is defined without a return type (void) but with two integer arguments (a and b). The function calculates the sum of the two numbers and displays the result. The function is called from the main function with num1 and num2 as arguments, resulting in the sum being printed.
This type of function returns a value but does not require any arguments.
#include <stdio.h> |
Output:
Random Number: <randomly generated number> |
In this example, the getRandomNumber function is defined with an integer return type. The function generates a random number between 0 and 99 using the rand function and returns it. The getRandomNumber function is called from the main function, and the returned random number is printed.
This type of function returns a value and requires one or more arguments.
#include <stdio.h> |
Output:
Maximum Number: 7 |
In this example, the findMax function is defined with an integer return type and two integer arguments (a and b). The function compares the two numbers and returns the maximum of the two. The findMax function is called from the main function with num1 and num2 as arguments, and the returned maximum number is printed.
Functions in the C language have three essential parts:
A function call invokes or executes a function in the program. It involves using the function name followed by parentheses, which may contain arguments (values or variables) to be passed to the function.
For example,
int area = getRectangleArea(5, 8); |
In this example, the getRectangleArea function is called with arguments 5 and 8, and the returned value is stored in the area variable.
A function declaration serves as a prototype for the function and provides information to the compiler about the user-defined function that may be used later in the code. It includes the function name, return type, and parameters (optional).
The function declaration syntax is as follows:
returnType functionName(type1 parameter1, type2 parameter2, ...); |
The return type indicates the data type returned by the function. The function name is a unique identifier for the function. Parameters specify the number and types of inputs the function accepts.
For example,
int getRectangleArea(int length, int breadth); |
A function definition in C contains the actual block of code executed when the function is called. It consists of several components that define the behaviour of the function.
Here are the different components of function definition -
Return Type:
The return type specifies the value's data type the function will return after its execution. It can be any valid C data type, such as int, float, char, void, etc. If the function does not return a value, the return type is specified as void.
Function Name:
The function name is a unique identifier for the function. It calls or invokes the function from other parts of the program. The function name should follow the rules for naming identifiers in C, such as starting with a letter or underscore, and can contain letters, digits, and underscores.
Parameter List:
The parameter list specifies the inputs or arguments the function expects to receive when called. Each parameter is defined with its data type and a parameter name. Commas separate multiple parameters. If the function does not require any parameters, an empty parameter list or void can be used.
Function Body:
The function body is enclosed within curly braces {} and contains a collection of statements defining the function's behaviour. It includes the code that is executed when the function is called.
Return Statement (if applicable):
If the function has a return type other than void, a return statement specifies the value the function will return. The return statement terminates the function's execution and returns the specified value to the caller.
The syntax for function definition is as follows:
returnType functionName(type1 parameter1, type2 parameter2, ...) { |
The function body consists of a collection of instructions that define what the function does. It may include variables, statements, and the return statement (if applicable) to return a value.
For example,
int getRectangleArea(int length, int breadth) { |
We use a function call to invoke a user-defined function in C and transfer control to that function. The function call consists of the function name followed by parentheses. If there are any arguments, they are passed within the parentheses.
Here is the syntax for calling a user-defined function in C:
functionName(argument1, argument2, ...); |
The function name is used to identify the specific function being called. The arguments (if any) are values or variables passed to the function. It's important to provide the arguments in the same order defined in the function declaration.
Let's consider an example to demonstrate a function call:
#include <stdio.h> |
Here, we have a user-defined function, ‘addNumbers’, comprising two integer arguments, x and y, which processes their sum as an integer. Within the main function, we declare two variables, num1, and num2, to hold the numbers we want to add. We then call the addNumbers function and pass the values of num1 and num2 as arguments. The returned sum is stored within sum variable and then printed to the console.
The output of the above program would be:
Sum: 15 |
When calling a function in C to calculate its output, we create a function call. The program's control is transferred to the called function, and its function body is executed. To make a function call, we use the function name along with the values of the arguments enclosed in round brackets in the exact order defined in the function declaration.
There are two types of function calls:
Call by Value:
The argument values are copied to the function parameters in a call-by-value function, and we cannot modify the actual values. Copies of the variables passed to the function are created, which remain in the stack segment of memory and are overwritten when the program leaves the scope of the called function.
Call by Reference:
In call by reference, the address of the arguments is passed to the function parameters, allowing us to modify the actual values of the arguments outside the function scope.
The return statement returns a value from a function and terminates its execution, returning control to the calling function. It allows us to return a result or output from the function to the calling code. The returned value must match the data type defined in the function declaration and definition.
Syntax of the return statement:
return expression; |
If present, the expression is evaluated, and its value is converted to the return type defined by the function. If a function has a return type of void, no return statement is required inside the function definition.
If no return statement exists in the function body, the program's control reaches the calling function after executing the last line. However, it is considered good practice to include a return statement, even for void functions, to clarify the intention.
The C compiler may warn if there is code after the return statement, indicating that it is unreachable and will never execute.
Example:
#include<stdio.h> |
Output:
3 / 2 = 1.5 |
In this example, the getRatio function calculates the ratio of two integers. To avoid integer division, we typecast the denominator to double. The calculated ratio is directly returned from the function and stored in a variable of type double in the main function. Finally, the ratio is printed to the console.
The return; statement can be used in functions with a return type of void to indicate an empty return expression as well.
Passing arguments to a function allows us to provide data to the function for it to perform operations or calculations. Arguments are the values we pass to a function during a call. These arguments are received by the function parameters, defined in the function declaration and used within the function's body.
For example, consider the function:
int getRectangleArea(int length, int breadth) { |
In this function, length and breadth are the function parameters. When calling this function, we pass values for length and breadth as arguments. In the main function, we can pass arguments like this:
int l = 5, b = 10; |
Here, l and b are the arguments being passed to the getRectangleArea function. These values are received by the function parameters' length and breadth within the function's scope.
It's important to ensure that the data types of the function arguments match the data types of the corresponding function parameters. If there is a mismatch, the compiler will throw an error.
When passing multiple arguments to a function, it's crucial to maintain the order of the arguments as defined in the function declaration. The arguments are passed in the same order as the parameters are declared.
A function can also be called without any arguments if the function does not require any input data. Additionally, there is no limit to the number of arguments that can be passed to a user-defined function in C.
User-defined functions in C play a crucial role in code organisation, modularity, and reusability. We can improve code readability and maintainability by breaking down complex tasks into smaller, manageable functions. With the ability to pass arguments and return values, functions allow us to create flexible and efficient code structures. By leveraging functions effectively, we can enhance code structure, promote code reuse, and make our programs more modular and manageable.
Students can also get an immersive learning experience with upGrad’s Executive Post Graduate Program in Data Science & Machine Learning course. This program can strengthen your decision-making skill while strengthening your programming abilities to hone proficiency in the competitive field of data science.
So, what are you waiting for, enroll now!
1. What do we mean by user-defined function types?
User-defined function types refer to the various categories or classifications of user-defined functions based on their characteristics and purposes, such as functions with return values, functions without return values, functions with parameters, etc.
2. What is the difference between a user-defined function and a library function?
The programmer creates a user-defined function to perform specific tasks based on program requirements. In contrast, a library function is predefined and provided by a library or framework, offering commonly used functionality that can be readily used in programs without explicit implementation.
3. Can a user-defined function call another user-defined function?
Yes, a user-defined function can call another user-defined function. Function calls can be nested within one another, allowing for modular and reusable code organisation. This enables the decomposition of complex tasks into smaller, manageable functions, enhancing code readability and maintainability.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...