That doesn't do what you think it does. You need to remove the semicolon after the end of the conditions on the if statement. You can only evaluate the variable your switching on against constants so you can't do this for example: case a < 80 && a > 69: That won't compile. The only way I am aware of that you could convert that into a switch statement would be like this:
1 2 3 4 5 6 7 8 9
switch(a)
{
case 70:
case 71:
case 72:
// all the way down to 79
case 79:
std::cout << "blah blah blah\n";
}
#include <iostream>
int main()
{
int a ;
std::cin >> a ;
// int( a>69 ) == 1 if a is greater than 69
// int( a<80 ) == 1 if a is less than 80
switch( (a>69) + 2 * (a<80) )
{
// a>69 == 1 and a<80 == 0
case 1 : std::cout << "a is greater than 79\n" ; break ;
// a>69 == 0 and a<80 == 1
case 2 : std::cout << "a is less than 70\n" ; break ;
// a>69 == 1 and a<80 == 1
case 3 : std::cout << "a is between 70 and 79 (inclusive)\n" ;
}
}
so then, most tutorials i've read say that switch is the better way to go, but it looks like there will be cases where if-else is the way to go then? guess i wasn't crazy. thanks
Yes. Use whatever best accommodates the situation. If you're checking against a string for example then obviously you'd use if-else. On the other hand if you're comparing integers or chars against a constant value then switch might be better suited for the task.