-
For() inside switch
Is it possible to put a for() loop inside a switch statement?
Code:
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int main()
{
for (int i=0; i < 8; i++)
{
switch (i)
{
case for (int j=0; i < 6; j++): //something like this?
cout<<"1-6"<<endl;
break;
case 7:
cout<<"7"<<endl;
break;
}
}
system("pause");
return 0;
}
-
Yes, but the for loop cannot be the label, of course.
-
Yes, but not the way you did it (as a label).
try this -
Code:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
cout<<"1-6"<<endl;
break;
if you need a very large range, consider using an if statement instead or in conjunction with the switch statement.
-
What you have there might better be written as
Code:
for (int i = 0; i < 7; ++i) {
std::cout << "0-6\n";
}
std::cout << "7\n";
-
the way to do what you're suggesting is to use fallthrough.
Code:
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int main()
{
for (int i=0; i < 8; i++)
{
switch (i)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6: {
cout<<"0-6"<<endl;
break;
}
case 7: {
cout<<"7"<<endl;
break;
}
}
}
system("pause");
return 0;
}
-
Code:
What you have there might better be written as
Yes i realized that. I was just trying to rewrite the same program with switch(), but it takes up much more space indeed.
Thanks everybody!