In your code, here:
if (0){
continue;
}
The integer literal 0
is contextually converted to bool
, the result is always false
(non-zero integers would yield true
). The if
statement can be removed without altering the behavior, because continue
is never actually executed:
int main() {
for (int i = 0; i<=15;i+=2){
cout<<i<<" ";
i++;
}
}
If possible either increment the counter in the body (of a while loop) or via the iteration-expression of the for loop, but not both. This is simpler and achieves the same as your code:
for (int i = 0; i<=15;i+=3){
cout<<i<<" ";
}
On the other hand, to get this output:
0 3 5 7 9 11 13 15
You can increment in every iteration by 2
, only in the first iteration, when i==0
you increment one additional time:
for (int i = 0; i<=15;i+=2){
cout<<i<<" ";
if (i == 0) ++i;
}
How does continue work. Does it skip if block only or whole for loop ?
continue
skips the remaining part of the enclosing loop. For details see here https://en.cppreference.com/w/cpp/language/continue.
why is it not going on i++?
In your code continue
has no effect on the following i++
because if(0)
is a dead branch.
If you want to use continue
you can turn above logic around and do the additional increment in every iteration, but before that you continue
when i
is not 0
:
for (int i = 0; i<=15;i+=2){
cout<<i<<" ";
if (i != 0) continue;
++i;
}
The condition can be written as if (i)
(see above, contextual conversion of 0
to bool
yields false
). Perhaps that is where you are coming from and instead of removing the != 0
you removed i !=
from the condition.