0

How is the switch statement executed here?
I am especially interested in the use of continue.

#include <stdio.h>

int main()
{
    char ch = 'A';
    while (ch <= 'D')
    {
        switch (ch)
        {
        case 'A':
        case 'B':
            ch++;
            continue;
        case 'C':
        case 'D':
            ch++;
        }
        printf("%c", ch);
    }
}

This outputs DE, as you can see live on coliru.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Triveni T
  • 19
  • 2

2 Answers2

0

Short answer: Continue corresponds to the while loop in the code.

Initially, value of ch is A and it matches the first case and since your cases don't have break, once a case is triggered, switch will go through all cases (until break, exit, continue, end of cases etc...). As a result it also enters case B and increments the ch to B. Since it encounters the continue it skips the rest of the instructions and begins the next iteration of the while loop.

You can run it in debugger to understand these things. You can also use the old-school printfs if needed.

There is also SO thread which discuss in detail about continue in switch

j23
  • 3,139
  • 1
  • 6
  • 13
0

Here in char variable ' A' is 65 and 'D' is 68 .If the char value less then or equal in the condition the while loop will run. then in switch condition ch is the value which you defined earlier then the variable value match with the condition of case and increase the value of ch

Tofael A.
  • 1
  • 1