ループの中で continue 文に出会うと、それ以降の処理を飛ばして次の回のループに移る。この時、for ループではインクリメント部が実行されてループ変数は変更される。
次のプログラムは、ユーザーに整数を複数入力させてその合計を出力する(0 で入力終了)。その際、整数を2回入力させて合致するかを確かめている。もし合致しない場合は入力された数を合計に加算せずに continue で次のループに処理が移る。
#include
int main(void)
{
int total, i, j;
total = 0;
do {
printf("Input number (0 to exit): ");
scanf("%d", &i);
printf("Once more: ");
scanf("%d", &j);
if (i != j) {
printf("Error: Try again.\n");
continue;
}
total = total + i;
} while (i);
printf("TOTAL: %d\n", total);
return 0;
}
実行例:
Input number (0 to exit): 1 Once more: 1 Input number (0 to exit): 5 Once more: 5 Input number (0 to exit): 9 Once more: 9 Input number (0 to exit): 0 Once more: 0 TOTAL: 15
実行例2(わざと間違った例):
takatoh@nightschool $ ./sample_3_8 Input number (0 to exit): 1 Once more: 2 Error: Try again. Input number (0 to exit): 1 Once more: 1 Input number (0 to exit): 5 Once more: 5 Input number (0 to exit): 0 Once more: 0 TOTAL: 6
最初の入力(1, 2)は合致しないので、合計に加算されていない。