C Function Prototypes
In this page:
What is a Function Prototype?
A function prototype declares a function's return type, name, and parameter types to the compiler before the function's full body appears later in the file, so the compiler knows how to correctly interpret any earlier calls to it.
Example: What is a Function Prototype?
#include <stdio.h>
int add(int a, int b);
int main() {
printf("%d", add(2, 3));
return 0;
}
int add(int a, int b) {
return a + b;
}
Login to try C/C++/Java/PHP code in the editor
Why Use Prototypes?
Because C compilers read a file top to bottom, calling a function before its definition appears would otherwise cause an error -- prototypes solve this by giving the compiler enough information about the function upfront.
Example: Why Use Prototypes?
#include <stdio.h>
int square(int n);
int main() {
printf("%d", square(4));
return 0;
}
int square(int n) {
return n * n;
}
Login to try C/C++/Java/PHP code in the editor
Prototype Syntax
A prototype repeats the function's header exactly as it will appear in the definition, but ends with a semicolon instead of a body, and the parameter names inside it are optional since only their types actually matter to the compiler.
Example: Prototype Syntax
#include <stdio.h>
int add(int, int);
int main() {
printf("%d", add(3, 4));
return 0;
}
int add(int a, int b) {
return a + b;
}
Login to try C/C++/Java/PHP code in the editor
Preventing Compiler Warnings
Modern compilers check every function call against its prototype's declared parameter types and count, catching mismatched arguments as a compile error rather than letting them slip through as a runtime bug.
Example: Preventing Compiler Warnings
#include <stdio.h>
int add(int a, int b);
int main() {
printf("%d", add(2, 3));
return 0;
}
int add(int a, int b) {
return a + b;
}
Login to try C/C++/Java/PHP code in the editor
Multiple Prototypes
Listing all of a program's function prototypes together near the top of the file is standard C practice, giving anyone reading the file a quick overview of every function it defines before digging into the implementations.
Example: Multiple Prototypes
#include <stdio.h>
int add(int a, int b);
int square(int n);
int main() {
printf("%d %d", add(2, 3), square(4));
return 0;
}
int add(int a, int b) {
return a + b;
}
int square(int n) {
return n * n;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: