+ 4
Can a program get inside to a multiple switch cases?
for example, in a C++ code I have: int i = 2; switch(i){ case 1: cout << "first case" << endl; case 2: cout << "second case" <<endl; case 3: cout << "third case"<<endl; default: cout <<"default case"<< endl; } I don't have clearly what is the output can anyone help me, plis? thanks psdt: sorry for any syntax error that I would have and for my english as well
3 Answers
+ 3
Think of the switch as a rope and cases as sections of rope
Like Nathan said, you have to add a break for each case.
If a case is true, in your example "case 2:", you have to cut the rope using "break;" so nothing after that point is considered.
+ 2
in your example, it would print "second case" then "third case", then "default case". If you add the "break" statement at the end of each of the case sections, you can control this behavior.
http://en.cppreference.com/w/cpp/language/switch
+ 2
yes, I know the use of break sentence, I just had that question in mind, thanks to all!