C

ภาษาที่อยู่เบื้องหลังระบบปฏิบัติการ ฐานข้อมูล และอุปกรณ์ฝังตัว เข้าใจ C แล้วจะเข้าใจว่าคอมพิวเตอร์ทำงานอย่างไร

ภาษา C คืออะไร

C เป็นภาษาโปรแกรมระดับกลางที่สร้างขึ้นในช่วงต้นทศวรรษ 1970 เพื่อเขียนระบบปฏิบัติการ Unix จนถึงวันนี้ยังเป็นภาษาหลักของ Linux kernel, ฐานข้อมูลอย่าง SQLite และ PostgreSQL, ตัวแปลภาษา Python (CPython) และเฟิร์มแวร์ในอุปกรณ์ฝังตัว

  • เร็วและเล็ก — คอมไพล์เป็นภาษาเครื่องโดยตรง ไม่มี garbage collector
  • ควบคุมหน่วยความจำเอง — ทรงพลัง แต่ผิดพลาดง่าย ต้องระวัง
  • พกพาได้ — มีคอมไพเลอร์สำหรับแทบทุกสถาปัตยกรรม
  • มาตรฐาน — C89, C99, C11, C17 และ C23 แนะนำให้เขียนตาม C11 หรือใหม่กว่า

ติดตั้งคอมไพเลอร์

ระบบวิธีติดตั้ง
Linux (Debian/Ubuntu)sudo apt install build-essential gdb valgrind
Linux (Fedora/RHEL)sudo dnf install gcc make gdb valgrind
macOSxcode-select --install (ได้ clang)
WindowsWSL (ติดตั้ง Ubuntu แล้วใช้คำสั่งแบบ Linux) หรือ MSYS2 แล้วติดตั้ง mingw-w64-ucrt-x86_64-gcc
# MSYS2 (เปิดเทอร์มินัล UCRT64)
pacman -S mingw-w64-ucrt-x86_64-gcc make

# ตรวจสอบว่าติดตั้งสำเร็จ
gcc --version

Hello World และการคอมไพล์

#include <stdio.h>

int main(void)
{
    printf("Hello, GoldRatch!\n");
    return 0;   /* 0 = จบการทำงานแบบสำเร็จ */
}
# คอมไพล์แบบเปิดคำเตือนทั้งหมดและใส่ข้อมูลดีบัก
gcc -std=c17 -Wall -Wextra -g hello.c -o hello
./hello

# เวอร์ชันสำหรับใช้งานจริง: เปิด optimization
gcc -std=c17 -Wall -Wextra -O2 hello.c -o hello
ตัวเลือกความหมาย
-Wall -Wextraเปิดคำเตือนที่สำคัญ ควรใช้เสมอ
-Werrorถือว่าคำเตือนเป็นข้อผิดพลาด
-gใส่ข้อมูลสำหรับ debugger (gdb)
-O0 / -O2ไม่ optimize / optimize ระดับใช้งานจริง
-std=c17กำหนดมาตรฐานภาษา
-o ชื่อชื่อไฟล์ผลลัพธ์
-cคอมไพล์เป็น object file (.o) โดยไม่ link
-lmlink ไลบรารีคณิตศาสตร์ (ใช้กับ math.h)

ชนิดข้อมูล printf และ scanf

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

int main(void)
{
    int age = 30;               /* อย่างน้อย 16 บิต ส่วนใหญ่ 32 บิต */
    long long big = 9000000000LL;
    double price = 129.50;
    char grade = 'A';
    bool active = true;         /* ต้อง include stdbool.h (ก่อน C23) */
    int32_t exact = 42;         /* ขนาดแน่นอน จาก stdint.h */
    size_t n = sizeof(double);  /* ขนาดเป็นไบต์ */

    printf("age=%d big=%lld price=%.2f grade=%c\n", age, big, price, grade);
    printf("active=%d exact=%d size=%zu\n", active, exact, n);

    int qty;
    printf("จำนวน: ");
    if (scanf("%d", &qty) != 1) {      /* ตรวจผลการอ่านเสมอ */
        fprintf(stderr, "กรุณากรอกตัวเลข\n");
        return 1;
    }
    printf("รวม %.2f บาท\n", qty * price);
    return 0;
}
รูปแบบใช้กับ
%d / %uint / unsigned int
%ld / %lldlong / long long
%f / %.2fdouble (ทศนิยม 2 ตำแหน่ง); scanf ใช้ %lf
%c / %sอักขระ / สตริง
%zusize_t
%pพอยน์เตอร์ (แปลงเป็น void *)
%xเลขฐาน 16

เงื่อนไข ลูป และฟังก์ชัน

#include <stdio.h>

/* ประกาศ prototype ก่อนใช้ */
int factorial(int n);
void print_grade(int score);

int main(void)
{
    for (int i = 1; i <= 5; i++) {
        printf("%d! = %d\n", i, factorial(i));
    }

    int count = 3;
    while (count > 0) {
        printf("นับถอยหลัง %d\n", count);
        count--;
    }

    print_grade(72);
    return 0;
}

int factorial(int n)
{
    return (n <= 1) ? 1 : n * factorial(n - 1);
}

void print_grade(int score)
{
    switch (score / 10) {
    case 10:
    case 9:  puts("A"); break;
    case 8:  puts("B"); break;
    case 7:  puts("C"); break;     /* อย่าลืม break */
    default: puts("ต้องปรับปรุง");
    }
}

อาร์เรย์และสตริง

สตริงใน C คืออาร์เรย์ของ char ที่ปิดท้ายด้วยอักขระ '\0' ไม่มีการเก็บความยาวไว้ และไม่มีการตรวจขอบเขตให้อัตโนมัติ

#include <stdio.h>
#include <string.h>

int main(void)
{
    int scores[5] = {80, 75, 92, 60, 88};
    size_t len = sizeof scores / sizeof scores[0];   /* จำนวนสมาชิก = 5 */

    int sum = 0;
    for (size_t i = 0; i < len; i++)
        sum += scores[i];
    printf("เฉลี่ย %.1f\n", (double)sum / len);

    char name[32] = "Gold";
    /* ต่อสตริงอย่างปลอดภัย: snprintf ไม่เขียนเกินขนาด buffer */
    char full[64];
    snprintf(full, sizeof full, "%sRatch", name);
    printf("%s (%zu ตัวอักษร)\n", full, strlen(full));

    if (strcmp(full, "GoldRatch") == 0)     /* เปรียบเทียบด้วย strcmp ไม่ใช่ == */
        puts("ตรงกัน");

    char line[100];
    if (fgets(line, sizeof line, stdin)) {  /* อ่านทั้งบรรทัดอย่างปลอดภัย */
        line[strcspn(line, "\n")] = '\0';   /* ตัด newline ท้ายบรรทัด */
        printf("คุณพิมพ์: %s\n", line);
    }
    return 0;
}

ระวัง: strlen นับเป็นไบต์ ข้อความภาษาไทยแบบ UTF-8 ใช้ 3 ไบต์ต่ออักขระ ดังนั้น strlen("ไทย") ได้ 9 ไม่ใช่ 3 ห้ามใช้ gets เด็ดขาด (ถูกถอดออกจากมาตรฐานแล้ว) ใช้ fgets แทน

พอยน์เตอร์และการจองหน่วยความจำ

พอยน์เตอร์คือตัวแปรที่เก็บที่อยู่ของตัวแปรอื่น &x คือที่อยู่ของ x และ *p คือค่าที่ p ชี้อยู่

#include <stdio.h>

void swap(int *a, int *b)       /* ส่งที่อยู่เข้ามา จึงแก้ค่าตัวจริงได้ */
{
    int t = *a;
    *a = *b;
    *b = t;
}

int main(void)
{
    int x = 1, y = 2;
    int *p = &x;
    *p = 10;                    /* x กลายเป็น 10 */
    swap(&x, &y);
    printf("x=%d y=%d\n", x, y);  /* x=2 y=10 */

    int arr[3] = {1, 2, 3};
    int *q = arr;               /* ชื่ออาร์เรย์แปลงเป็นพอยน์เตอร์ไปสมาชิกตัวแรก */
    printf("%d\n", *(q + 2));   /* เท่ากับ arr[2] = 3 */
    return 0;
}

malloc และ free

หน่วยความจำที่จองด้วย malloc/calloc/realloc อยู่บน heap และอยู่จนกว่าจะเรียก free

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    size_t n = 5;
    int *data = malloc(n * sizeof *data);
    if (data == NULL) {                 /* ตรวจว่าจองสำเร็จ */
        perror("malloc");
        return 1;
    }
    for (size_t i = 0; i < n; i++)
        data[i] = (int)(i * i);

    /* ขยายขนาด: ใช้ตัวแปรชั่วคราว ป้องกันข้อมูลเดิมหายถ้า realloc ล้มเหลว */
    int *tmp = realloc(data, 2 * n * sizeof *data);
    if (tmp == NULL) {
        free(data);
        return 1;
    }
    data = tmp;

    free(data);
    data = NULL;                        /* ป้องกันการใช้หลัง free */
    return 0;
}

Struct

#include <stdio.h>
#include <string.h>

typedef struct {
    int id;
    char name[50];
    double balance;
} Customer;

void deposit(Customer *c, double amount)
{
    c->balance += amount;              /* -> ใช้กับพอยน์เตอร์ไปยัง struct */
}

int main(void)
{
    Customer c = { .id = 1, .name = "สมชาย", .balance = 500.0 };
    deposit(&c, 250.0);
    printf("%d %s %.2f\n", c.id, c.name, c.balance);   /* . ใช้กับตัว struct */

    Customer list[2] = {
        { 2, "สมหญิง", 1000.0 },
        { 3, "สมศักดิ์", 0.0 },
    };
    for (int i = 0; i < 2; i++)
        printf("%s\n", list[i].name);
    return 0;
}

Header file และ Makefile

โปรแกรมขนาดใหญ่แยกเป็นหลายไฟล์: ไฟล์ .h เก็บการประกาศ ไฟล์ .c เก็บโค้ดจริง ใช้ include guard ป้องกันการ include ซ้ำ

/* mathx.h */
#ifndef MATHX_H
#define MATHX_H

int add(int a, int b);
double average(const int *values, int count);

#endif
/* mathx.c */
#include "mathx.h"

int add(int a, int b) { return a + b; }

double average(const int *values, int count)
{
    if (count <= 0) return 0.0;
    long sum = 0;
    for (int i = 0; i < count; i++) sum += values[i];
    return (double)sum / count;
}
/* main.c */
#include <stdio.h>
#include "mathx.h"

int main(void)
{
    int v[] = {4, 8, 15};
    printf("%d %.2f\n", add(2, 3), average(v, 3));
    return 0;
}

Makefile คอมไพล์เฉพาะไฟล์ที่เปลี่ยน (บรรทัดคำสั่งใต้ target ต้องขึ้นต้นด้วย Tab ไม่ใช่ช่องว่าง)

CC     = gcc
CFLAGS = -std=c17 -Wall -Wextra -g
OBJS   = main.o mathx.o

app: $(OBJS)
	$(CC) $(CFLAGS) -o $@ $(OBJS)

%.o: %.c mathx.h
	$(CC) $(CFLAGS) -c $<

clean:
	rm -f app $(OBJS)
make          # สร้างโปรแกรม app
make clean    # ลบไฟล์ที่สร้าง

บั๊กที่พบบ่อยและเครื่องมือหาบั๊ก

บั๊กตัวอย่างวิธีป้องกัน
Buffer overflowเขียน arr[5] ในอาร์เรย์ขนาด 5, strcpy ข้อความยาวเกินตรวจขอบเขต ใช้ snprintf, fgets
Use-after-freeใช้พอยน์เตอร์หลัง freeตั้งเป็น NULL หลัง free
Double freeเรียก free ซ้ำสองครั้งกำหนดเจ้าของหน่วยความจำให้ชัด
Memory leakmalloc แล้วไม่ freefree ทุกเส้นทางที่ออกจากฟังก์ชัน
ตัวแปรไม่กำหนดค่าint sum; sum += 1;กำหนดค่าเริ่มต้นทุกครั้ง เปิด -Wall
= แทน ==if (x = 5)อ่านคำเตือนของคอมไพเลอร์
Integer overflowint คูณกันจนเกินช่วงใช้ชนิดที่ใหญ่พอ เช่น int64_t

AddressSanitizer, Valgrind และ gdb

# AddressSanitizer: จับ overflow / use-after-free ตอนรัน (gcc และ clang)
gcc -g -fsanitize=address,undefined -fno-omit-frame-pointer main.c -o app
./app

# Valgrind (Linux): ตรวจ memory leak และการอ่านหน่วยความจำผิด
valgrind --leak-check=full ./app

# gdb: หยุดที่ฟังก์ชัน ดูค่าตัวแปร
gdb ./app
(gdb) break main
(gdb) run
(gdb) next
(gdb) print sum
(gdb) backtrace

เคล็ดลับ: ระหว่างพัฒนา ให้คอมไพล์ด้วย -Wall -Wextra -g -fsanitize=address,undefined เป็นค่าเริ่มต้น บั๊กหน่วยความจำส่วนใหญ่จะถูกจับได้ทันทีพร้อมบอกบรรทัดที่ผิด ส่วนการทำงานบนเซิร์ฟเวอร์ Linux ดูเพิ่มได้ที่ Linux (Unix)

แหล่งเรียนรู้ต่อ