|
問(wèn)題:
#include <stdio.h>
int main() { // int a; // int a; for(int i=0;i<5;i++) { int b; b++; printf("%d",b); } return 0; } 上面這個(gè)程序在for循環(huán)中多次int b都沒(méi)有關(guān)系,程序都正確。 但是下面的程序在for循環(huán)外多次int a就出現(xiàn)錯(cuò)誤了,請(qǐng)問(wèn)為什么呢? #include <stdio.h> int main() { int a; int a; for(int i=0;i<5;i++) { int b; b++; printf("%d",b); } return 0; } 解答:
下面你的程序出現(xiàn)了重復(fù)定義的錯(cuò)誤,即一個(gè)程序中不能同時(shí)定義同名的兩個(gè)變量,你在程序中int a; 后變量a的作用域是全局的,定義第二個(gè)int a;后作用域也是全局的,這是絕對(duì)不允許的。
上面的代碼中,你在for循環(huán)中定義了int b; 變量b的作用域就在for循環(huán)體內(nèi),循環(huán)一次后局部變量b就會(huì)消失,當(dāng)執(zhí)行第二次for循環(huán)時(shí),會(huì)重新定義局部變量b,不會(huì)出現(xiàn)重復(fù)定義。因此編譯時(shí)不會(huì)出錯(cuò)!?。? |
|
|
來(lái)自: dingzi4178 > 《程序語(yǔ)言》