Declaring and Defining Functions in C programming
Declaring and Defining Functions in C
In C programming, functions are used to perform specific tasks. Functions need to be declared before they are used, and then defined with their actual implementation. Here’s how you can do it:
Function Declaration (Prototype)
A function declaration, or prototype, tells the compiler about the function's name, return type, and parameters, but does not provide the body of the function.
return_type function_name(parameter_list);
Example:
int add(int a, int b); // Function prototype
This declaration tells the compiler that there is a function named add
that takes two int
parameters and returns an int
.
Function Definition
A function definition provides the actual implementation of the function. It includes the function’s body, where the task is performed.
return_type function_name(parameter_list) {
// Function body
}
Example:
int add(int a, int b) {
return a + b; // Function body
}
This definition provides the actual code for the add
function, which adds the two integer parameters and returns the result.
Example Program
#include <stdio.h>
// Function prototype (declaration)
int add(int a, int b);
int main() {
int num1 = 5;
int num2 = 7;
int result;
// Function call
result = add(num1, num2);
// Print the result
printf("The sum of %d and %d is %d\\n", num1, num2, result);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
This program demonstrates how to declare and define a function. It includes a function prototype, a function definition, and a function call from the main
function.
Always declare functions before using them in your code to avoid compilation errors. The function prototype provides the necessary information to the compiler about the function's return type and parameters.
Comments
Post a Comment