Function Declaration: A function declaration tells the compiler about the function name, return type, and parameters. It is also known as a function prototype. It is usually placed at the beginning of the code or in a header file. This allows the compiler to ensure that function calls match the declared parameters and return type.
Function Prototype: A function prototype specifies the function’s interface without the body of the function. It includes the return type, the function name, and the parameter list with their types.
Here’s a simple example to demonstrate the function declaration and prototype in C:
#include <stdio.h>
// Function prototype
void greet(char name[]);
int main() {
printf("Program started.\n");
// Calling the function
greet("Alice");
printf("Program ended.\n");
return 0;
}
// Function definition
void greet(char name[]) {
printf("Hello, %s! Welcome to the program!\n", name);
}
Function Prototype:
void greet(char name[]);
This line is the function prototype. It tells the compiler that there is a function named greet that takes a char array (string) as an argument and returns nothing (void). The function prototype is declared before the main function.
Function Call:
greet("Alice");
Inside the main function, the greet function is called with the argument "Alice".
Function Definition:
void greet(char name[]) { printf("Hello, %s! Welcome to the program!\n", name);
}
This is the function definition. It provides the actual implementation of the greet function. When greet is called, it prints a welcome message that includes the provided name.