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

Storage Classes ในโปรแกรม C


ตัวแปรและชนิดข้อมูลได้กล่าวไปแล้ว ตอนนี้เราจะดูว่าตัวแปรสามารถจัดหมวดหมู่ได้อย่างไรจาก scope และ visibility

Scope: หมายถึง lifetime ของตัวแปร จะทำงานนานแค่ไหน และเมื่อไหร่จะถูกทำลาย

Visibility: แสดงว่าตัวแปรมองเห็นได้จากที่ไหน สามารถใช้ได้ที่ไหน เช่น local variables ไม่สามารถใช้จากฟังก์ชันหรือไฟล์อื่นได้ มองเห็นได้เฉพาะใน block

Block: ชุดบรรทัดระหว่าง curly braces {…}

Storage ClassHow has DeclaredScopeVisibility
autoGlobally

autoLocallyBlockBlock
registerGlobally

registerLocallyBlockBlock
staticGloballyProgramFile
staticLocallyProgramBlock
externGloballyProgramProgram
externLocallyProgramBlock

Basic Syntax สำหรับ storage class:

<storage class> <datatype> variable_name; ex. static int my_var = 0;

Note: ถ้าใช้ <datatype> variable_name; โดยไม่ระบุ storage class จะเป็น 'auto' อัตโนมัติ

Auto: default storage class สำหรับ local variables ทั้งหมด

{    int mount;    auto int month; }

'auto' ใช้ได้เฉพาะในฟังก์ชัน คือ local variables

Register: ใช้กำหนด local variables ที่ควรเก็บใน register แทน RAM หมายถึงตัวแปรมีขนาดสูงสุดเท่ากับ register size (ปกติ 1 word) และไม่สามารถใช้ unary '&' operator ได้ (เพราะไม่มี memory location)

{    register int miles; }

register ควรใช้กับตัวแปรที่ต้องการ quick access เช่น counters การประกาศ 'register' ไม่ได้หมายความว่าจะเก็บใน register จริง แต่อาจจะเก็บขึ้นอยู่กับ hardware และ implementation restrictions

Static: สั่ง compiler เก็บ local variable ไว้ตลอด lifetime ของโปรแกรม แทนที่จะสร้างและทำลายทุกครั้งที่เข้าและออก scope ทำให้ local variables static สามารถรักษาค่าระหว่าง function calls ได้

static modifier ยังใช้กับ global variables ได้ เมื่อทำเช่นนั้น จะจำกัด scope ของตัวแปรให้อยู่ในไฟล์ที่ประกาศเท่านั้น

ใน C เมื่อ static 用於 global variable จะทำให้มีเพียงหนึ่ง copy ของ member นั้นถูก share โดย objects ทั้งหมดของ class

ตัวอย่างโค้ด

#include <stdio.h> /* function declaration */ void func(void); static int count = 5; /* global variable */ main() {    while(count--) {       func();    }    return 0; } /* function definition */ void func( void ) {    static int i = 5; /* local static variable */    i++;    printf("i is %d and count is %d\n", i, count); }

ผลลัพธ์

i is 6 and count is 4 i is 7 and count is 3 i is 8 and count is 2 i is 9 and count is 1 i is 10 and count is 0

Extern: ใช้ให้ reference ของ global variable ที่มองเห็นได้จาก ALL program files เมื่อใช้ 'extern' ตัวแปรไม่สามารถ initialize ได้ แต่ชี้ไปที่ storage location ที่เคย define ไปแล้ว

เมื่อมีหลายไฟล์ และ define global variable หรือ function ที่จะใช้ในไฟล์อื่น extern จะใช้ในอีกไฟล์หนึ่งเพื่อให้ reference ของ variable หรือ function ที่ define ไว้

ตัวอย่างโค้ด (main.c):

#include <stdio.h> int count ; extern void write_extern(); main() { count = 5; write_extern(); } Example Code (support.c): #include <stdio.h> extern int count; void write_extern(void) { printf("count is %d\n", count); }

ผลลัพธ์

count is 5