Storage class ระบุ scope, lifetime และ binding ของตัวแปร
เพื่อกำหนดตัวแปรให้สมบูรณ์ ต้องระบุไม่แค่ 'type' แต่ גם storage class
ชื่อตัวแปรระบุตำแหน่งในหน่วยความจำที่จัดสรรบิตสำหรับเก็บค่า
Storage class บอกข้อมูลต่อไปนี้:
- ตัวแปรเก็บที่ไหน (memory หรือ CPU register)?
- ค่าเริ่มต้นคืออะไรถ้าไม่ได้ initialize?
- Scope ของตัวแปรคืออะไร (เข้าถึงได้ที่ไหน)?
- อายุของตัวแปรนานแค่ไหน?
Binding
Binding หา declaration/definition ที่ตรงกับการใช้งาน (usage) ของ identifier
- ต้องรู้ Scope ของตัวแปร
Block structure คืออะไร? ตัวระบุอยู่ในบล็อกไหน?
- เกิดอะไรขึ้นถ้าใช้ชื่อ identifier ซ้ำ?
C ห้ามใช้ชื่อ identifier ซ้ำใน scope เดียวกัน แต่วางได้ใน scope ต่างกัน
ตัวอย่างผิด
double f, y;
int f() // error
{
---
}
double y; // errorตัวอย่างถูกต้อง
double y;
int f() {
double f; // legal
int y; // legal
}ตัวอย่างโปรแกรม Binding
#include <stdio.h>
int i = 33;
int main() {
extern int i;
{
int i = 22;
{
const volatile unsigned i = 11;
printf("i=%d\n", i);
}
printf("i=%d", i);
}
return 0;
}ผลลัพธ์
i=11 i=22