C語言的do-while語句的兩種寫法
while循環和for循環都是入口條件循環,即在循環的每次迭代之前檢查測試條件,所以有可能根本不執行循環體中的內容。C語言還有出口條件循環(exit-condition loop),即在循環的每次迭代之后檢查測試條件,這保證了至少執行循環體中的內容一次。這種循環被稱為do while循環。
看下面的例子:
- #include <stdio.h>
- int main(void)
- {
- const int secret_code = 13;
- int code_entered;
- do
- {
- printf("To enter the triskaidekaphobia therapy club,\n");
- printf("please enter the secret code number: ");
- scanf("%d", &code_entered);
- } while (code_entered != secret_code);
- printf("Congratulations! You are cured!\n");
- return 0;
- }
運行結果:
- To enter the triskaidekaphobia therapy club,
- please enter the secret code number: 12
- To enter the triskaidekaphobia therapy club,
- please enter the secret code number: 14
- To enter the triskaidekaphobia therapy club,
- please enter the secret code number: 13
- Congratulations! You are cured!
使用while循環也能寫出等價的程序,但是長一些,如程序清單6.16所示。
- #include <stdio.h>
- int main(void)
- {
- const int secret_code = 13;
- int code_entered;
- printf("To enter the triskaidekaphobia therapy club,\n");
- printf("please enter the secret code number: ");
- scanf("%d", &code_entered);
- while (code_entered != secret_code)
- {
- printf("To enter the triskaidekaphobia therapy club,\n");
- printf("please enter the secret code number: ");
- scanf("%d", &code_entered);
- }
- printf("Congratulations! You are cured!\n");
- return 0;
- }
下面是do while循環的通用形式:
- do
- statement
- while ( expression );
statement可以是一條簡單語句或復合語句。注意,do-while循環以分號結尾。

Structure of a =do while= loop=
do-while循環在執行完循環體后才執行測試條件,所以至少執行循環體一次;而for循環或while循環都是在執行循環體之前先執行測試條件。do while循環適用于那些至少要迭代一次的循環。例如,下面是一個包含do while循環的密碼程序偽代碼:
- do
- {
- prompt for password
- read user input
- } while (input not equal to password);
避免使用這種形式的do-while結構:
- do
- {
- ask user if he or she wants to continue
- some clever stuff
- } while (answer is yes);
這樣的結構導致用戶在回答“no”之后,仍然執行“其他行為”部分,因為測試條件執行晚了。