Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Tầm quan trọng của function prototype trong C

Ở đây ta xem tại sao nên dùng function prototype trong C. Prototype cho trình biên dịch biết: số đối số, kiểu tham số, kiểu trả về. Trình biên dịch cross-check chữ ký trước khi gọi. Không có prototype có thể compile với warning hoặc output lạ.

Nếu hàm 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