如何僅使用 goto 陳述句實作 do-while 回圈?
do{
// some code
}
while ();
像這樣,但只使用 goto 來創建等價物
uj5u.com熱心網友回復:
do{
// some code
}
while (condition);
等于:
label:
{
// some code
}
if(condition) goto label;
uj5u.com熱心網友回復:
在 C 中向上使用跳轉陳述句被認為是非常糟糕的做法,也稱為意大利面條式編程。所以你的問題的答案是:在 C 中不存在有效的用例goto,你永遠不應該寫這樣的代碼。時期。
goto 在某些特殊情況下,例如錯誤處理程式,向下可能是可以接受的。
uj5u.com熱心網友回復:
do-while 回圈是 while 回圈的變體。條件由 while 回圈檢查,陳述句在 do 段中。
do{
statement(s);
}while(condition);
您可以使用 goto.like 來完成相同的作業,而不是使用 for、while、do while 回圈
int i = 0;
firstLoop:
printf("%d",i);
i ;
if(i<10)
goto firstLoop;
printf("\nout of first loop");
但建議不要使用 goto 陳述句。您通過使用 goto 陳述句實作的目標,可以使用其他一些條件陳述句(如if-else等)更輕松地實作。
uj5u.com熱心網友回復:
這很容易做到。
對于初學者,您應該考慮到 do-while 陳述句的主體構成了塊作用域,即使主體不是由復合陳述句表示的。例如這個程式是正確的。
#include <stdio.h>
int main(void)
{
struct A
{
int s;
};
do
printf( "sizeof( struct A { int x; int y; } ) = %zu\n",
sizeof( struct A { int x; int y; } ) );
while ( sizeof( struct A ) == 8 );
printf( "sizeof( struct A ) = %zu\n",
sizeof( struct A ) );
return 0;
}
程式輸出是
sizeof( struct A { int x; int y; } ) = 8
sizeof( struct A ) = 4
也就是說,在 do-while 陳述句的子陳述句中宣告的結構 A 在其自身的內部作用域內,相對于撰寫 do-while 陳述句的作用域以及定義具有一個資料成員的結構 A 的作用域而言。每次當子陳述句獲得控制權時,都會重新宣告結構 A。
使用goto陳述句重寫的 do-while 陳述句將如下面的演示程式所示。在這種情況下,您需要使用復合陳述句來引入內部作用域。
#include <stdio.h>
int main(void)
{
struct A
{
int s;
};
L1:
{
printf( "sizeof( struct A { int x; int y; } ) = %zu\n",
sizeof( struct A { int x; int y; } ) );
}
if ( sizeof( struct A ) == 8 ) goto L1;
printf( "sizeof( struct A ) = %zu\n",
sizeof( struct A ) );
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/341517.html
上一篇:為什么我沒有收到一個“i”變數?
