查看了很多資料都說:goto到標簽以后就按照順序執行,這個標簽只是一個跳轉地址跟作用域真沒什么關系。但是goto有作用范圍,文件內。(我想應該是正確吧!)可是我發現 C Primer Plus 中文第五版 181 頁的例子:(1) if(size > 12)goto a;goto b;a: cost = cost * 1.05flag = 2;b: bill = cost * flag;書上說等效于:if(size > 12){cost = cost * 1.05;flag = 2;}bill = cost * flag;按照網上的理論(goto到標簽以后就按照順序執行):為什么不是?if(size > 12){cost = cost * 1.05;flag = 2;bill = cost * flag;}bill = cost * flag;(2) if(ibex > 14)goto a;sheds = 2;goto b;a: sheds = 3;b: help = 2 * sheds;書上說等效于:if(ibex > 14)sheds = 3;elsesheds = 2;help = 2 * sheds;同理,按照網上的理論(goto到標簽以后就按照順序執行):為什么不是?if(ibex > 14){sheds = 3;help = 2 * sheds;}elsesheds = 2;help = 2 * sheds;
2 回答

DIEA
TA貢獻1820條經驗 獲得超2個贊
標簽本身沒有作用域的,只是一個標志點。
但是goto本身有限制,只能是當前函數。所以,從這個角度來說,標簽的作用域也可以說是當前函數。
比如
void func() { int a; a=0; loop: a++; if (a<10) goto loop; printf ( "%d" ,a); } |
這個程序中,loop標簽就與goto配合起到了跳轉作用。
對于goto來說,這個標簽只要是在本函數內的就是合法的,無論是在goto前還是goto后。
但是,如下程序:
int a = 0; void func1( void ) { loop: printf ( "%d" ,a); } void func2( void ) { a++; if (a<10) goto loop; } |
在func2中調用goto使用了func1中的標簽loop,在編譯的時候就會報錯。因為使用goto時只會在本函數中查找該標簽。

ibeautiful
TA貢獻1993條經驗 獲得超6個贊
if (ibex > 14) sheds = 3; else sheds = 2; help = 2 * sheds; |
與
有區別嗎?這2個是沒有任何區別的。
在你看來,區別是help = 2 * sheds;這句話的地方,但是,你發現了沒有,無論是上面的一個,還是下面的一個。不管if語句成立或者不成立,help = 2 * sheds;這句語句都是會執行的。所以,雖然在寫法上有一點區別,但是結果確實完全是一樣的。
這也是一種簡潔程序的一種思路,你現在有可能體會不到,等你以后編寫多了,你就能體會到這種簡潔的思路了。
添加回答
舉報
0/150
提交
取消