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

Inline Function ในภาษา C คืออะไร

Inline function = ฟังก์ชันที่ compiler อาจแทนที่การเรียกด้วยโค้ดจริง (function substitution) เพื่อลด overhead

คุณสมบัติ

  • เหมาะสำหรับฟังก์ชันเล็ก คำนวณเร็ว
  • ไม่เหมาะฟังก์ชันใหญ่/ซับซ้อน
  • เพิ่ม keyword inline หน้าฟังก์ชัน
  • เป็นเพียงคำแนะนำ compiler ตัดสินใจเอง

Syntax

inline return_type function_name(parameters) {
    // body
}

โปรแกรมตัวอย่าง

#include <stdio.h>
inline int mul(int a, int b) {
    return a * b;
}
int main() {
    int c = mul(2, 3);
    printf("Multiplication: %d\n", c);
    return 0;
}

ผลลัพธ์

Multiplication: 6