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

ประเภทของฟังก์ชันในภาษา C: Predefined vs User-defined

ฟังก์ชันใน C แบ่งใหญ่ 2 ประเภท:

1. Predefined / Library Functions (ฟังก์ชันไลบรารี)

  • กำหนดไว้ใน System Libraries แล้ว
  • นำมาใช้งานได้เลย ต้อง Include Header ที่เหมาะสม
  • โปรแกรมเมอร์ต้องรู้ Syntax/Parameters

ตัวอย่างยอดนิยม

FunctionHeaderDescription
printf()<stdio.h>พิมพ์ข้อความจัดรูปแบบ
scanf()<stdio.h>อ่าน Input จัดรูปแบบ
sqrt()<math.h>รากที่สอง
pow()<math.h>ยกกำลัง
strlen()<string.h>ความยาวสตริง
strcpy()<string.h>คัดลอกสตริง
malloc()<stdlib.h>จองหน่วยความจำ Dynamic
qsort()<stdlib.h>Quick Sort

ตัวอย่าง: ใช้ sqrt()

#include <stdio.h>
#include <math.h>

int main() {
    int x;
    printf("Enter positive number: ");
    scanf("%d", &x);
    
    double y = sqrt(x);
    printf("Square root = %.2f\n", y);
    return 0;
}

2. User-defined Functions (ฟังก์ชันที่ผู้ใช้สร้าง)

  • โปรแกรมเมอร์เขียนเอง ตามความต้องการ
  • ต้อง Define เอง ก่อนใช้ (หรือมี Prototype)
  • ไม่ต้อง Include Header เพิ่ม
  • ยืดหยุ่น ปรับแต่งได้ตามต้องการ

ตัวอย่าง: ฟังก์ชันคำนวณผลรวม

#include <stdio.h>

// Prototype
int sum(int a, int b);

int main() {
    int a, b, c;
    printf("Enter 2 numbers: ");
    scanf("%d %d", &a, &b);
    
    c = sum(a, b);  // เรียกใช้
    printf("Sum = %d\n", c);
    return 0;
}

// Definition
int sum(int a, int b) {
    return a + b;
}

ผลลัพธ์

Enter 2 numbers: 10 20
Sum = 30

เปรียบเทียบ

ลักษณะLibrary FunctionsUser-defined Functions
ผู้สร้างCompiler/Standard LibraryProgrammer
Header ที่ต้อง Includeต้อง Includeไม่ต้อง (แต่ควรมี Prototype)
การแก้ไขไม่ได้ (Standard)ได้ตามต้องการ
Portabilityสูง (ANSI C)ขึ้นกับการเขียน
PerformanceOptimizedขึ้นกับการ Implement

แนวทาง: สร้าง Library เอง

รวม User-defined Functions ที่ใช้บ่อยเป็น Header File (.h) และ Source File (.c) เพื่อนำกลับมาใช้ซ้ำได้

// mymath.h
#ifndef MYMATH_H
#define MYMATH_H
int add(int a, int b);
int max(int a, int b);
#endif

// mymath.c
#include "mymath.h"
int add(int a, int b) { return a + b; }
int max(int a, int b) { return (a > b) ? a : b; }

// main.c
#include <stdio.h>
#include "mymath.h"

int main() {
    printf("Max: %d\n", max(10, 20));
    return 0;
}