重複執行 語句,直到expression評估為零為止。
語法
while ( expression )
statement
備註
表達式的測試會在每次執行迴圈之前進行;因此,while迴圈會執行零次或多次。
表達式 必須是整數類型、指標類型,或具有明確轉換成整數或指標類型的類別類型。
執行while語句主體內的中斷、goto 或傳回時,迴圈也可以終止。 使用 繼續 終止目前的反覆專案,而不結束 while 迴圈。
continue 將控件傳遞至迴圈的 while 下一個反覆專案。
下列程式代碼會使用 while 循環來修剪字串的尾端底線:
// while_statement.cpp
#include <string.h>
#include <stdio.h>
char *trim( char *szSource )
{
char *pszEOS = 0;
// Set pointer to character before terminating NULL
pszEOS = szSource + strlen( szSource ) - 1;
// iterate backwards until non '_' is found
while( (pszEOS >= szSource) && (*pszEOS == '_') )
*pszEOS-- = '\0';
return szSource;
}
int main()
{
char szbuf[] = "12345_____";
printf_s("\nBefore trim: %s", szbuf);
printf_s("\nAfter trim: %s\n", trim(szbuf));
}
終止條件在迴圈頂端進行評估。 如果沒有結尾底線,此迴圈絕不會執行。
另請參閱
反覆運算陳述式
關鍵字
do-while 陳述式 (C++)
for 陳述式 (C++)
以範圍為基礎的 for 陳述式 (C++)