ความหมายของ Variable
Variable คือชื่อของตำแหน่งหน่วยความจำ ที่ใช้เก็บค่าข้อมูล ค่าสามารถเปลี่ยนแปลงได้ตลอดการทำงานของโปรแกรม
ควรตั้งชื่อให้สื่อความหมาย เช่น sum, average, total, student_count
กฎการตั้งชื่อตัวแปร (Naming Rules)
- ขึ้นต้นด้วยตัวอักษร (a-z, A-Z) หรือ underscore (_)
- ความยาวสูงสุด 31 ตัวอักษร (ANSI C) แต่คอมไพเลอร์สมัยใหม่รองรับมากกว่า
- Case-sensitive:
total, TOTAL, Totalคือคนละตัวแปร - ห้ามเป็น Keywords (int, if, while, for, return, switch, etc.)
- ห้ามมี whitespace (space, tab, newline)
- อักขระที่อนุญาต: ตัวอักษร, ตัวเลข, underscore (_) เท่านั้น
ตัวอย่างชื่อที่ถูกต้อง/ผิด
| ถูกต้อง | ผิด | เหตุผล |
|---|---|---|
| count, total_sum, _temp, x1 | 123abc | ขึ้นต้นด้วยตัวเลข |
| studentName, MAX_SIZE | my-variable | มี hyphen (-) |
| _private, PI_VALUE | int | เป็น keyword |
| my var | มี space |
Variable Declaration
Syntax
datatype v1, v2, ..., vn;
ตัวอย่าง
int sum; float a, b, c; char grade, initial;
ขอบเขตของตัวแปร (Scope)
Local Declaration
ประกาศภายใน block (function) ใช้ได้เฉพาะใน block นั้น
int main() {
int local_var = 10; // local to main
// ...
}Global Declaration
ประกาศนอกฟังก์ชันทุกตัว ใช้ได้ทั่วโปรแกรม (file scope, external linkage)
int global_var = 100; // global
void func() { global_var = 200; } // เข้าถึงได้ตัวอย่างโปรแกรม: Local และ Global Variables
#include <stdio.h>
int a, b; // global declaration
int main() {
int c; // local declaration
// ...
}ตัวอย่างโปรแกรม: คำนวณกำไร/ขาดทุน
#include <stdio.h>
int main() {
float costPrice, sellingPrice, amount;
printf("ราคาทุน: ");
scanf("%f", &costPrice);
printf("ราคาขาย: ");
scanf("%f", &sellingPrice);
if (sellingPrice > costPrice) {
amount = sellingPrice - costPrice;
printf("กำไร = %.4f\\n", amount);
} else if (costPrice > sellingPrice) {
amount = costPrice - sellingPrice;
printf("ขาดทุน = %.4f\\n", amount);
} else {
printf("ไม่กำไรไม่ขาดทุน\\n");
}
return 0;
}ผลลัพธ์ตัวอย่าง
ราคาทุน: 240 ราคาขาย: 280 กำไร = 40.0000
Best Practices
- ประกาศตัวแปรใกล้จุดที่ใช้งานที่สุด (C99+)
- Initialize ตอนประกาศ:
int count = 0; - ใช้ชื่อที่อธิบายตัวเอง (self-documenting)
- หลีกเลี่ยง global variables มากเกินไป
- ใช้ const สำหรับค่าคงที่:
const float PI = 3.14159;