Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

วัตถุประสงค์ของ Function Prototype ใน C/C++

Function Prototype บอกคอมไพเลอร์ล่วงหน้าเกี่ยวกับ: จำนวนพารามิเตอร์ ชนิดข้อมูลพารามิเตอร์ และ Return Type

ประโยชน์:

  • Cross-check Function Signature ก่อนเรียกใช้
  • ป้องกัน Warning/Error จาก Implicit Declaration
  • อนุญาตให้เรียกฟังก์ชันก่อน Definition ได้

ตัวอย่างโดยไม่มี Prototype (มี Warning)

main() { function(50); }
void function(int x) { printf("%d", x); }
// Warning: conflicting types for 'function'

ตัวอย่างมี Prototype (ไม่มี Warning)

void function(int); // Prototype
main() { function(50); }
void function(int x) { printf("%d", x); }