Странная работа continue в цикле while
#include <stdio.h>
int main(void) {
int i = 0;
do {
printf("%d", i++);
if(i == 1) continue;
} while(i == 0);
}
Почему программа выводит только 0, а не 01?
Ответы (3 шт):
continue не пропускает условие цикла, а только оставшуюся часть тела.
У вас после него в теле ничего нет, поэтому оно ни на что не влияет.
мы вначале попадаем в блок do. там вызывается
printf("%d", i++);
так как изначально i = 0; печатается: "0", а затем только увеличивается.
после printf у нас i = 1; дальше пытаемся перейти на следующую итерацию. но так как в условии:
while(i == 0);
выходим из цикла. Поэтому да, напечатается только один раз
Для инструкции continue стандарт дает не двусмысленное объяснение для каждого из циклов:
The continue statement shall occur only in an iteration-statement and causes control to pass to the loopcontinuation portion of the smallest enclosing iteration-statement, that is, to the end of the loop. More precisely, in each of the statements
while (foo) { do { for (;;){ { { { // ... // ... // ... } } } contin: ; contin: ; contin: ; } } while(foo) }a continue not contained in an enclosed iteration statement is equivalent to
goto contin.