Function prototype cho trình biên dịch biết: số lượng đối số, kiểu dữ liệu tham số, kiểu trả về. Trình biên dịch cross-check chữ ký hàm trước khi gọi. Nếu không có prototype, có thể compile với warning hoặc output lạ.
Nếu hàm được gọi trước khi định nghĩa, trình biên dịch không biết chữ ký. Cần prototype. Nếu định nghĩa trước thì không cần.
Ví dụ không prototype (có warning)
#include <stdio.h>
int main() {
function(50);
}
void function(int x) {
printf("The value of x is: %d", x);
}
Kết quả
The value of x is: 50 [Warning] conflicting types for 'function' [Note] previous implicit declaration of 'function' was here
Ví dụ có prototype (không warning)
#include <stdio.h>
void function(int); // prototype
int main() {
function(50);
}
void function(int x) {
printf("The value of x is: %d", x);
}
Kết quả
The value of x is: 50