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

Macros vs Functions ในภาษา C

Macro: Pre-processed (Text Substitution) ก่อนคอมไพล์
Function: Compiled เป็น Machine Code

ปัญหาของ Macro

  • ไม่มี Type Checking
  • Debug ยาก (แทนที่ข้อความโดยตรง)
  • ไม่มี Namespace (ชนกันได้)
  • เพิ่มขนาดโค้ด (Code Bloat)
  • ไม่ตรวจสอบ Compile-time Error

ตัวอย่างปัญหา: SQUARE Macro

#define SQUARE(x) x * x
int sqr(int x) { return x * x; }

main() {
    printf("sqr(3+2) = %d\n", sqr(3+2));     // 25
    printf("SQUARE(3+2) = %d\n", SQUARE(3+2)); // 11 (3 + 2 * 3 + 2)
}

Macro ขยายเป็น 3 + 2 * 3 + 2 = 11 ในขณะที่ฟังก์ชันคำนวณ (3+2)*(3+2) = 25