ตัวแปรภายนอกเรียกอีกอย่างว่าตัวแปรส่วนกลาง ตัวแปรเหล่านี้ถูกกำหนดไว้ภายนอกฟังก์ชันและพร้อมใช้งานทั่วโลกตลอดการทำงานของฟังก์ชัน คีย์เวิร์ด “extern” ใช้เพื่อประกาศและกำหนดตัวแปรภายนอก
คีย์เวิร์ด [ extern “C” ] ใช้เพื่อประกาศฟังก์ชันใน C++ ซึ่งใช้งานและคอมไพล์ในภาษา C ใช้ไลบรารี C ในภาษา C++
ต่อไปนี้เป็นวากยสัมพันธ์ของ extern
extern datatype variable_name; // variable declaration using extern extern datatype func_name(); // function declaration using extern
ที่นี่
ประเภทข้อมูล − ประเภทข้อมูลของตัวแปร เช่น int, char, float เป็นต้น
variable_name − นี่คือชื่อของตัวแปรที่กำหนดโดยผู้ใช้
func_name − ชื่อของฟังก์ชัน
ต่อไปนี้เป็นตัวอย่างภายนอก:
ตัวอย่าง
#include <stdio.h>
extern int x = 32;
int b = 8;
int main() {
extern int b;
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 extern variables x and b : 32,8 The value of modified extern variable x : 15
ในโปรแกรมข้างต้น ตัวแปร x และ b สองตัวถูกประกาศเป็นตัวแปรส่วนกลาง
extern int x = 32; int b = 8;
ในฟังก์ชัน main() ตัวแปรจะเรียกว่า extern และค่าต่างๆ จะถูกพิมพ์
extern int b;
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);