ตัวแปรภายนอก (External variables) เรียกอีกอย่างว่า ตัวแปรกลโบล (Global variables) ประกาศนอกฟังก์ชัน ใช้งานได้ทั่วโปรแกรม ค่าสามารถเปลี่ยนแปลงได้จากฟังก์ชันใดๆ ใช้คำสำคัญ extern ประกาศและนิยาม
- ขอบเขต: ทั่วโปรแกรม (global)
- ค่าเริ่มต้น: 0
- อายุการใช้งาน: จนจบโปรแกรม
จุดสำคัญ
- ประกาศได้หลายครั้ง แต่นิยามได้เพียงครั้งเดียว
externขยายขอบเขตการมองเห็นของฟังก์ชันหรือตัวแปร- ฟังก์ชันเป็น global โดยปกติ ไม่ต้องประกาศ extern
- ตัวแปรที่มี
externเป็นการประกาศ (declaration) ไม่ใช่นิยาม (definition) - การกำหนดค่าเริ่มต้นให้ extern ถือเป็นนิยาม
ตัวอย่าง
#include <stdio.h>
extern int x = 32;
int b = 8;
int main() {
auto int a = 28;
extern int b;
printf("The value of auto variable : %d\n", a);
printf("The value of extern variables x and b : %d,%d\n", x, b);
x = 15;
printf("The value of modified extern variable x : %d\n", x);
return 0;
}ผลลัพธ์
The value of auto variable : 28 The value of extern variables x and b : 32,8 The value of modified extern variable x : 15