-9

Here is the programm:

#include <iostream>
#include <string>
using namespace std;
string add(string s, int n) {
 switch (n%3) {
 case 2: s = s + "A";
 case 1: s = s + "B";
 break;
 default: s = s + "C";
 }
 return s;
}
int main() {
 string s{"X"};

 for (size_t i{0}; i < 6; ++i)
 s = add(s, i);
 cout << s;
 return 0;
}

And I expected output: XCBACBA

But correct output is:XCBABCBAB

Can you explain me an algorithm? it seems, that i don't understand the logic begind switch statement(and how does absence of break after case 2 influence on the result?)

soc5
  • 9
  • 1
  • 4
  • 1
    If you don't put a break into your case statement the next case statement will also be executed. – xyious Oct 30 '17 at 21:18
  • 2
    Perfect time to learn how to use your debugger. – Richard Critten Oct 30 '17 at 21:18
  • 2
    SO is not meant to be used as a tutorial service. Consider the following options: 1) Reading a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to understand how `switch` statement works. 2) Step through the code with a debugger, to figure out how the code is executed line-by-line. – Algirdas Preidžius Oct 30 '17 at 21:18

3 Answers3

1

There is no break after

case 2: s = s + "A";

There should be one just like

case 1: s = s + "B";
 break;
Einārs
  • 240
  • 2
  • 13
1

The break statement is how you leave the switch statement. If you don't have it at the end of a case, it keeps running with the next case. So your code is effectively equivalent to:

switch(n%3) {
case 2:
    s = s + "A";
    s = s + "B";
    break;
case 1:
    s = s + "B";
    break;
default:
    s = s + "C";
}

That's why your output always has an extra B after A.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

In C++, if you omit a break at the end of a case statement, execution will fall through to the next case.

In your code this means that for case 2, both s = s + "A"; and s = s + "B"; will be executed.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536