#include <iostream>
int main() {
int n = 3, i=0;
switch (n % 2)
{
case 0:
do {
++i;
case 1:
++i;
} while (--n > 0);
}
std::cout << i;
}
Why is the output 5 and not 6 ? Can someone explain it to me more detailed ?
Basically, when you enter the 'switch' you jump inside the loop body. Then the loop is executed ignoring the label 'case 1'.
It is like executing the following lines of code.
I never suggest a code style like that, because it is harder to maintain. I prefer instead a structured code. The style of your example reminds me the C64 Basic or Assembly.
While this code style is deprecable, the C language (C++ too) is flexible enough to allow you this. Take care because jumping randomly around could decrease the optimizer performance. At the end your code could run slower than the structured solution.