Defining a function in C involves specifying the return type, function name, parameters (if any), and the body of the function. Let’s walk through an example of defining a simple function that calculates the square of a number:
#include <stdio.h>
// Function declaration or prototype
int square(int num);
// Function definition
int square(int num) {
int result = num * num;
return result;
}
int main() {
int number = 5;
int squaredNumber = square(number); // Calling the square function
printf(“The square of %d is %d\n”, number, squaredNumber);
return 0;
}
In this example:
- Function Declaration:
- Before the main() function, we declare the square() function using a function prototype. This tells the compiler about the function’s existence, its return type (int), and the type of its parameter (int).
- Function Definition:
- The square() function is defined after the main() function. It specifies the return type (int), function name (square), and the parameter (int num) within parentheses.
- Inside the function body, we calculate the square of the num parameter and assign it to a variable result.
- Finally, we return the result using the return statement.
- Function Call:
- Inside the main() function, we call the square() function with an argument (number), which is passed to the num parameter of the square() function.
- The result returned by the square() function is stored in the variable squaredNumber.
- Output:
- The printf() function is used to print the result, displaying the original number and its square.
Defining functions in C allows for code reuse and modularization. Once defined, functions can be called multiple times from different parts of the program, making the code more organized, readable, and easier to maintain.