User Defined Functions in C
User-defined functions in C are custom tools that programmers create to perform specific tasks in their code. They simplify complex processes, making the program more organized and manageable. By using these functions, developers can avoid repetition, enhance readability, and make their code more efficient. Let's dive into how you can craft these functions to tailor your applications perfectly.
How Can We Use User Defined Functions in C
Incorporating user-defined functions into your C programs involves grasping the basics of their structure. Essentially, crafting a custom function is a three-step process:
- Declaring the Function Prototype
- Defining the Function
- Calling the Function
Declaring the Function Prototype
Think of the function prototype as an introduction of your function to the compiler. It outlines the function’s name, the types of parameters it expects, and its return type, serving as a forward declaration.
Syntax:
In prototypes, it's optional to name the parameters; you can simply mention their types.
Defining the Function
The function definition is where the action happens. Here, you specify what the function actually does through a series of statements wrapped in braces.
Syntax:
Note that if the function is defined before it's called in your program, you can skip the prototype declaration and go straight to defining it.
Calling the Function
To put your function to work, you need to call it by its name, followed by parentheses enclosing any arguments it requires.
Syntax:
Elements of User Defined Functions 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. 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: Specifies the type of data a function returns. Use void for functions without return values. It precedes the function's name in its declaration.
- Function Name: A unique identifier for the function, allowing it to be called. Valid names may include letters, underscores, and digits (but cannot start with a digit). Examples:
- thisIsAfunction() (valid)
- _getMaximum() (valid)
- !getMinimum() (invalid - symbols other than underscores are not allowed)
- getPowerOf2() (valid)
- 2Root() (invalid - cannot start with a digit)
- Parameter List: Lists the function's parameters, informing the compiler about the number and types of arguments it expects.
- Semicolon: Marks the end 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 in a function declaration.
Function body contains a collection of instructions that define what function does. 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.
Calling User Defined Functions in C
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 is called, in this case sum(10,5), control shifts from the calling function (main()) to the called function (sum()). Once sum() completes, control returns to main(), and any return value, like the sum in this case, is stored in a variable, e.g., ans, within main().
Syntax for function call
A function call requires the function name and arguments within parentheses. Arguments must match the order declared.
Creating a function call
To execute a function, use its name followed by arguments in parentheses, reflecting the declaration order. For instance, getRectangleArea(length, breadth) becomes:
where getRectangleArea(l, b) executes and returns the result to area.
There are two types of function calls
1. Call by value
In call by value function, arguments are copied to parameters, preventing the original values from being modified. Copies exist in the stack and are discarded after execution.
Output
2. Call by reference
In this approach, arguments' addresses are passed, allowing changes to persist beyond the function's scope.
Output
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.
The return statement exits a function, sending control back to the caller, and optionally passes back a value. It resumes execution right after the function call. The return type must align with the function's declared return type.
Syntax:
The expression is evaluated and converted to the function's return type. Void functions don't need a return statement; omitting it returns control to the caller post the last function line. While not required for void functions, using a return statement is advisable. C assumes int as the default return type, warning about code after a return statement.
Example:
Output:
This example demonstrates casting the denominator to double to avoid integer division, directly returning the calculated value.
For void functions, use return; for exiting without returning a value, as shown:
Examples of User Defined Functions in C
Here is an example to calculate area of 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 global array fibo.
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.
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().
4. Function with a return value and with an argument
Output
Passing Arguements to User Defined Functions in C
Data is passed to functions as arguments. For instance, in the function getRectangleArea, l and b are arguments passed during its call, corresponding to the parameters length and breadth within the function. These parameters access the passed values:
The data type of arguments and parameters must match, or the compiler will report an error. Parameters should be passed in the order they're defined. Functions can be called with no arguments and there's no limit on the number of arguments that can be passed.
Conclusion
- User-defined functions are essential for creating organized, efficient, and readable code, allowing developers to encapsulate and reuse logic.
- Crafting a function involves three key steps: declaring a prototype, defining the function, and calling it in your program.
- Function definitions contain the executable code, where parameters are utilized, and operations are performed to achieve the function's purpose.
- Calling a function activates it, executing its code with the provided arguments, showcasing the power and flexibility of user-defined functions in C programming.