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

การประกาศตัวแปรและกฎการตั้งชื่อในภาษา C

ความหมายของ Variable

Variable คือชื่อของตำแหน่งหน่วยความจำ ที่ใช้เก็บค่าข้อมูล ค่าสามารถเปลี่ยนแปลงได้ตลอดการทำงานของโปรแกรม

ควรตั้งชื่อให้สื่อความหมาย เช่น sum, average, total, student_count

กฎการตั้งชื่อตัวแปร (Naming Rules)

  1. ขึ้นต้นด้วยตัวอักษร (a-z, A-Z) หรือ underscore (_)
  2. ความยาวสูงสุด 31 ตัวอักษร (ANSI C) แต่คอมไพเลอร์สมัยใหม่รองรับมากกว่า
  3. Case-sensitive: total, TOTAL, Total คือคนละตัวแปร
  4. ห้ามเป็น Keywords (int, if, while, for, return, switch, etc.)
  5. ห้ามมี whitespace (space, tab, newline)
  6. อักขระที่อนุญาต: ตัวอักษร, ตัวเลข, underscore (_) เท่านั้น

ตัวอย่างชื่อที่ถูกต้อง/ผิด

ถูกต้องผิดเหตุผล
count, total_sum, _temp, x1123abcขึ้นต้นด้วยตัวเลข
studentName, MAX_SIZEmy-variableมี hyphen (-)
_private, PI_VALUEintเป็น 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;