Elements of User-Defined Functions
Every user-defined function consists of the following key elements:
Function Declaration (Prototype): Declares the function's name, return type, and parameters before the main()
function or other functions.
Function Definition: Contains the actual code block where the function's logic is implemented.
Function Call: Invokes the function by its name, passing arguments if
required.
Function Name: An identifier that is used to call the function. It should be descriptive of the function's purpose, e.g., add
.
Parameters: Variables that receive input values when the function is called. For example, in int add(int a, int b)
, a
and b
are parameters.
Return Type: The data type of the value that the function returns. This can be any valid C data type, such as int
, float
, char
, etc. If a function does not return a value, its return type is void
.
Function Body: The block of code that defines what the function does. This is enclosed in curly braces { }
and can contain variable declarations, statements, and control structures.
Example Code:
#include <stdio.h>
// Function Declaration (Prototype)
int multiply(int a, int b);
// Main Function
int main() {
int num1 = 4, num2 = 5;
int product = multiply(num1, num2); // Function Call
printf("The product is: %d\n", product);
return 0;
}
// Function Definition
int multiply(int a, int b) { // Parameters (a and b) and Return Type (int)
return a * b; // Returns the product of a and b
}
Output
This example demonstrates the main elements of a user-defined function:
Function Declaration: The line int multiply(int a, int b);
informs the compiler of the function name, its return type, and its parameter types.
Function Call: The multiply(num1, num2)
statement in main()
executes the function, passing num1
and num2
as arguments.
Function Definition: The block int multiply(int a, int b)
provides the actual instructions for the function, calculating and returning the product.
Parameters: a
and b
are input values that the function uses to perform its task.
Return Type: The function returns an integer result, indicated by int
in the declaration and definition.
Each of these elements plays a vital role in creating efficient, reusable, and well-structured code.