+ 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

31st Dec 2016, 3:44 AM
Juan Pablo Arango A.
Juan Pablo Arango A. - avatar
3 Respostas
+ 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.
31st Dec 2016, 4:11 AM
Vishal++
Vishal++ - avatar
+ 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
31st Dec 2016, 4:06 AM
Nathan
Nathan - avatar
+ 2
yes, I know the use of break sentence, I just had that question in mind, thanks to all!
31st Dec 2016, 4:15 AM
Juan Pablo Arango A.
Juan Pablo Arango A. - avatar