C语言基础教程读书笔记5.2.(第五章函数和存储类2)
4.作用域規(guī)則
??
標示符只能在說明或?qū)λx它的函數(shù)體或分程序內(nèi)飾可見的,而在該函數(shù)體或分程序外則是不可見的。
舉個例子:
# include <stdio.h>
int main()
{?
???? int a=2,b=4,c=6;
???? printf("%d,%d,%d\n",a,b,c);? //2,4,6
???? {
???????? int b=8;
???????? float c=8.8;
???????? printf("%d,%d,%.1f\n",a,b,c);?? //2,8,8.8
???????? a=b;
???????? {
????????????? int c;
????????????? c=b;
????????????? printf("%d,%d,%d\n",a,b,c);? //8,8,8
???????? }
???????? printf("%d,%d,%.1f\n",a,b,c);?? //8,8,8.8
???? }
???? printf("%d,%d,%d\n",a,b,c);? //8,4,6
???? getchar();
}
結(jié)果為:
?
?
?
5.存儲類
存儲類分為:
自動存儲(auto)、寄存器存儲(register)、外部類變量(extern)、靜態(tài)類變量(static)
我們下面來舉幾個例子說明一下不同存儲類變量的定義和特性。
1)局部變量的定義和應(yīng)用:
# include <stdio.h>
int main()
{
void other();
int a;
register int b;
static int c;
a=6;
b=9;
printf("a=%d,b=%d,c=%d\n",a,b,c);
other();
other();
printf("a=%d,b=%d,c=%d\n",a,b,c);
getchar();getchar();
}
void other()
{
int a=6;
static int b=10;
a+=100;
b+=200;
printf("a=%d,b=%d\n",a,b);
}
結(jié)果為:
簡單講一下:(main函數(shù)中定義了自動變量a,寄存器類變量b和內(nèi)部靜態(tài)類變量c,在函、數(shù)other()中,定義了一個自動變量a和內(nèi)部靜態(tài)變量b,(函數(shù)名與main中相同,但不影響,因為他們作用范圍在各自的函數(shù)體內(nèi)。)第一次調(diào)用other()函數(shù)時,輸出a和b的值分別為106和210,由于這里變量b是內(nèi)部靜態(tài)類的,其壽命長,在退出other()函數(shù)后仍然保存其值不被釋放。由于b變量的值被保存,在第二次調(diào)用other()函數(shù)時,因為靜態(tài)變量僅在編譯時初始化,因此b保留上次調(diào)用后的值在經(jīng)過b+=200)。
2)全局變量和局部變量的應(yīng)用
# include <stdio.h>
int main()
{ void other();
extern int i;
int a=0;
static int b;
printf("i=%d,a=%d,b=%d\n",i,a,b);
a+=5;
other();
printf("i=%d,a=%d,b=%d\n",i,a,b);
i+=10;
other();
getchar();
}
int i=7;
void other()
{
static int a=2;
int b=5;
i+=5;
a+=3;
b+=1;
printf("i=%d,a=%d,b=%d\n",i,a,b);
}
結(jié)果為:
講一下(由于外部變量i定義在主函數(shù)后,在主函數(shù)要引用i時,必須要用extern int i,語句進行說明,因為i在mian和other兩個函數(shù)中均可見,所以i值無論在main函數(shù)或是other中改變都是有效的,對后面的操作均有影響)。
3)多文件程序中的作用域
# include <stdio.h> //主程序
int i;
void fun1(),fun2(),fun3();
int main()
{
i=33;
fun1();
printf("main():i=%d\n",i);
fun2();
printf("main():i=%d\n",i);
fun3();
printf("main():i=%d\n",i);
getchar();
} //主程序
# include <stdio.h> //fun1
static int i;
void fun1()
{
i=100;
printf("fun1():i=(staic)=%d\n",i);
} // fun1
# include <stdio.h> //fun2
void fun2()
{
int i=5;
printf("fun():i(auto)=%d\n",i);
if(i)
{
extern int i;
printf("fun2():i(extern)=%d\n",i);
}
}
extern int i;
void fun3()
{
i=20;
printf("fun3():i(extern)=%d\n",i);
if(i)
{
int i=10;
printf("fun3():i(auto)=%d\n",i);
}
} //fun2
結(jié)果為:
解釋一下(在分程序中重新定義了變量b和c并賦初值,這時函數(shù)體外定義的b和c被隱藏起來,重新定義的b和c在起作用,a被重新復(fù)制,而非被重新定義)
轉(zhuǎn)載于:https://blog.51cto.com/2948229/1161838
總結(jié)
以上是生活随笔為你收集整理的C语言基础教程读书笔记5.2.(第五章函数和存储类2)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle技术之检查点及SCN号(一)
- 下一篇: 双语站,根据访客自动跳转js