#include <stdio.h>
int main(void) {
int score = 72;
if (score >= 90) {
printf("A\n");
} else if (score >= 60) {
printf("Pass\n");
} else {
printf("Fail\n");
}
return 0;
}
if เลือกทางที่จริง; else เลือกทางที่เท็จ
2.2
สวิตช์
A switch เลือกหนึ่ง case ตามจำนวนเต็ม ใช้ break เพื่อข้ามออกเมื่อเคสควรสิ้นสุด หากไม่มีการโอนการควบคุม การดำเนินการจะไหลต่อไปยังเคสถัดไป ซึ่งอาจเป็นการตั้งใจ default จะรันเมื่อไม่มีอะไรตรง
#include <stdio.h>
int main(void) {
int day = 3;
switch (day) {
case 1: printf("Mon\n"); break;
case 2: printf("Tue\n"); break;
case 3: printf("Wed\n"); break;
default: printf("Other\n");
}
return 0;
}
ข้อผิดพลาดที่พบบ่อย
if (x = 5) เป็นการกำหนดค่าเสมอและเป็นจริงเสมอ; ให้ใช้ == เพื่อเปรียบเทียบ
ฟังก์ชันรับพารามิเตอร์ (อินพุต) และส่งค่ากลับออกมา返回值 type มาไว้ก่อน (int, double, …); void หมายความว่าไม่ส่งอะไรกลับมาเลย
#include <stdio.h>
int square(int x) { // x is a parameter
return x * x; // hand back a value
}
int main(void) {
int r = square(5);
printf("%d\n", r); // 25
return 0;
}
พารามิเตอร์เข้า; ค่าส่งออก
4.2
โปรโตไทป์และสโคป
C อ่านจากบนลงล่าง ดังนั้นฟังก์ชันต้องถูกรู้จักก่อนจะถูกเรียกใช้ โปรโตไทป์ — บรรทัดหัวพร้อม ; — ประกาศมันล่วงหน้าเพื่อให้คุณสามารถวาง main ไว้ก่อนได้ สโคปของตัวแปรคือบล็อกที่มันอาศัยอยู่: มันเป็นแบบท้องถิ่นและหายไปเมื่อบล็อกสิ้นสุดลง
#include <stdio.h>
int add(int a, int b); // prototype: declared before use
int main(void) {
printf("%d\n", add(3, 4)); // 7
return 0;
}
int add(int a, int b) { // definition comes later
int sum = a + b; // sum is local to add
return sum;
}
ข้อผิดพลาดที่พบบ่อย
ฟังก์ชันที่ถูกเรียกใช้ก่อนการนิยามจำเป็นต้องมี prototype ด้านบน main
อาร์กิวเมนต์ถูกส่ง BY VALUE — การเปลี่ยนแปลงภายในฟังก์ชันจะไม่ส่งผลต่อผู้เรียกใช้เว้นแต่คุณจะส่งพอยน์เตอร์
อาเรย์เก็บหลายค่าของชนิดเดียวกัน ดัชนีเริ่มตั้งแต่ 0 C ไม่ เก็บความยาวของอาเรย์ ดังนั้นเทคนิคทั่วไปคือการคำนวณจำนวนองค์ประกอบ: sizeof(a) / sizeof(a[0])
#include <stdio.h>
int main(void) {
int scores[3] = {88, 71, 95};
printf("%d\n", scores[0]); // 88
scores[1] = 100;
printf("%d\n", scores[1]); // 100
int n = sizeof(scores) / sizeof(scores[0]);
printf("%d\n", n); // 3
return 0;
}
ช่องอาเรย์มีดัชนีเริ่มจาก 0
5.2
อัลกอริทึมอาเรย์
วนลูปผ่านอาร์เรย์ด้วย for เพื่อหาค่าสูงสุด ค่ารวม หรือจำนวน Always loop from 0 up to n - 1.
#include <stdio.h>
int main(void) {
int a[] = {3, 9, 2, 7};
int n = sizeof(a) / sizeof(a[0]);
int max = a[0], total = 0;
for (int i = 0; i < n; i++) {
if (a[i] > max) max = a[i];
total += a[i];
}
printf("%d %d\n", max, total); // 9 21
return 0;
}
#include <stdio.h>
void addOne(int *p) { // p holds an address
*p = *p + 1; // change the value at that address
}
int main(void) {
int x = 10;
int *ptr = &x; // & takes the address of x
printf("%d\n", *ptr); // * reads the value: 10
addOne(&x);
printf("%d\n", x); // 11 — changed through the pointer
return 0;
}
#include <stdio.h>
void swap_values(int a, int b) { // copies: the caller sees nothing
int t = a; a = b; b = t;
}
void swap_pointers(int *a, int *b) { // addresses: the swap is real
int t = *a; *a = *b; *b = t;
}
int main(void) {
int x = 1, y = 2;
swap_values(x, y);
printf("%d %d\n", x, y); // 1 2 (unchanged!)
swap_pointers(&x, &y);
printf("%d %d\n", x, y); // 2 1 (swapped)
return 0;
}
struct รวมค่าที่เกี่ยวข้องเข้าด้วยกันเป็นชนิดหนึ่ง ค่าแต่ละค่าคือสมาชิก typedef ให้ชื่อสั้นแก่ struct เพื่อให้คุณสามารถเขียน Dog แทนที่จะเป็น struct Dog ใช้ . กับค่า struct แต่ใช้ -> กับพอยน์เตอร์ไปยัง struct
#include <stdio.h>
typedef struct {
char name[20];
int age;
} Dog;
int main(void) {
Dog d = {"Rex", 3};
printf("%s is %d\n", d.name, d.age); // Rex is 3 (. on a value)
Dog *p = &d;
p->age = 4; // -> on a pointer
printf("%s is %d\n", d.name, d.age); // Rex is 4
return 0;
}
malloc allocates memory on the heap at run time and returns a pointer to it. realloc resizes that block; free gives it back. Every malloc needs a matching free, or you get a memory leak. These live in <stdlib.h>.
Locals live on the stack; malloc memory lives on the heap until you free it
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 3;
int *a = malloc(n * sizeof(int)); // room for 3 ints
if (a == NULL) return EXIT_FAILURE;
for (int i = 0; i < n; i++) a[i] = i * 10;
int *grown = realloc(a, 4 * sizeof *a); // positive size
if (grown == NULL) {
free(a);
return EXIT_FAILURE;
}
a = grown;
a[3] = 30;
for (int i = 0; i < 4; i++) printf("%d ", a[i]);
printf("\n"); // 0 10 20 30
free(a); // hand the memory back
return 0;
}
calloc(n, size) จัดสรร array เหมือน malloc AND เติมด้วยเลขศูนย์ทั้งหมด.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node *next;
} Node;
int main(void) {
Node *head = NULL;
for (int v = 10; v <= 30; v += 10) { // prepend 10, 20, 30
Node *n = malloc(sizeof(Node));
n->value = v;
n->next = head;
head = n;
}
for (Node *p = head; p != NULL; p = p->next) {
printf("%d ", p->value); // 30 20 10
}
printf("\n");
while (head != NULL) { // free the whole list
Node *t = head;
head = head->next;
free(t);
}
return 0;
}
10.2
Stacks & queues
Stack เป็น LIFO (last in, first out): push และ pop ที่ปลายเดียวกัน Queue เป็น FIFO (first in, first out): เพิ่มที่ท้าย ลบที่หน้า ทั้งสองสร้างง่ายบน array โดยใช้ index variables.
#include <stdio.h>
int main(void) {
int stack[10];
int top = 0; // next free slot
stack[top++] = 1; // push
stack[top++] = 2;
stack[top++] = 3;
while (top > 0) {
printf("%d ", stack[--top]); // pop: 3 2 1
}
printf("\n");
return 0;
}
#include <stdio.h>
int main(void) {
int queue[10];
int front = 0, back = 0;
queue[back++] = 1; // enqueue
queue[back++] = 2;
queue[back++] = 3;
while (front < back) {
printf("%d ", queue[front++]); // dequeue: 1 2 3
}
printf("\n");
return 0;
}
Linear search ตรวจสอบแต่ละ element ตามลำดับ — ใช้ได้กับ array ใดก็ได้ Binary search เร็วกว่ามากแต่ต้องต้องการ array ที่เรียงลำดับแล้ว: ตรวจสอบกลางและตัดครึ่งออกทุกขั้นตอน ทั้งสอง return index หรือ -1 หากไม่พบ.
#include <stdio.h>
int linear(int a[], int n, int target) {
for (int i = 0; i < n; i++)
if (a[i] == target) return i;
return -1;
}
int binary(int a[], int n, int target) {
int lo = 0, hi = n - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (a[mid] == target) return mid;
else if (a[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
int main(void) {
int a[] = {2, 5, 8, 12, 16, 23};
int n = sizeof(a) / sizeof(a[0]);
printf("%d %d %d\n", linear(a, n, 12), binary(a, n, 12), binary(a, n, 9));
return 0; // 3 3 -1
}
Linear scan ทั้งหมด; binary ลดเหลือครึ่งหนึ่งของช่วงที่เรียงแล้ว
Bit คือ 0 หรือ 1 เดี่ยว; numbers เก็บใน binary. Bitwise operators ทำงานกับ bits โดยตรง: & AND, | OR, ^ XOR, << shift left (×2 ทุกขั้น), >> shift right (÷2).
#include <stdio.h>
int main(void) {
int a = 12; // 1100
int b = 10; // 1010
printf("%d\n", a & b); // 8 AND -> 1000
printf("%d\n", a | b); // 14 OR -> 1110
printf("%d\n", a ^ b); // 6 XOR -> 0110
printf("%d\n", a << 1); // 24 left shift
printf("%d\n", a >> 1); // 6 right shift
return 0;
}
#include <stdio.h>
int main(void) {
printf("%d\n", 0xFF); // 255 (0x marks a hex literal)
printf("%x\n", 255); // ff
printf("%x\n", 12); // c
return 0;
}
Bitwise operators ทำงานกับ bits ของ integers
13.2
Run-length encoding
Run-length encoding (RLE) เป็นวิธี compression แบบง่าย: แทนที่ run ของ characters ซ้ำๆ ด้วย count และ character. It is lossless — สามารถกู้คืนต้นฉบับได้เต็มที่.
#include <stdio.h>
#include <string.h>
int main(void) {
char *s = "aaabbc";
int n = strlen(s);
for (int i = 0; i < n; ) {
char c = s[i];
int run = 0;
while (i < n && s[i] == c) { run++; i++; }
printf("%d%c", run, c); // 3a2b1c
}
printf("\n");
return 0;
}
ข้อผิดพลาดที่พบบ่อย
& คือ bitwise AND และ && คือ logical AND —อย่าสับสนกัน
#include <stdio.h>
#define MAX 100 // macro: text replaced before compiling
enum Color { RED, GREEN, BLUE }; // named integers 0, 1, 2
int next_id(void) {
static int count = 0; // keeps its value between calls
count++;
return count;
}
int main(void) {
const double PI = 3.14; // cannot be changed
printf("%d %.2f\n", MAX, PI); // 100 3.14
printf("%d %d %d\n", RED, GREEN, BLUE); // 0 1 2
int a = next_id();
int b = next_id();
printf("%d %d\n", a, b); // 1 2
return 0;
}
โปรแกรมใหญ่แบ่งข้ามไฟล์: declarations อยู่ใน header file (mine.h), include ด้วย #include "mine.h" —เครื่องหมายคำพูดหมายถึงไฟล์ของคุณเอง, < > หมายถึง standard library. Include guard (#ifndef MINE_H / #define MINE_H / #endif) ป้องกันการ include header ซ้ำ.
ข้อผิดพลาดที่พบบ่อย
#define ทำ plain text replacement โดยไม่มี type checking; ห่อหุ้ม macro bodies และ arguments ไว้ในวงเล็บ.
ค่าของ const ไม่สามารถเปลี่ยนแปลงได้หลังจากตั้ง.
ตัวแปร local ของ static คงค่าไว้ระหว่าง calls ของฟังก์ชัน.