Switch and do-while in c++

167 Views Asked by At
#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 ?

2

There are 2 best solutions below

0
Gildos On

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;
--n;
++i;
++i;
--n;
++i;
++i;
--n;

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.

2
Nishant On

as n%2 = 1 then after the switch statement yo go to the case 1 which is in do while, so you entered in the do while then these lines will be exectued

++i // then i = 1
--n // now n = 2 which is >0
++i // i = 2
++i // i = 3
--n // now n = 1 which is > 0
++i // i = 4
++i // i = 5
--n //  now n = 0 and does not satisfy the condition so the loop breaks and i = 5