switch question

i did a simple test program using if - else statements and i am converting it to the switch statement but not doing to good.

 
  if (a < 80 && a > 69); cout << "blah blah blah" << endl;


i dont know ho to make this line work with the case statement. it doesnt seem to like the function in parentheses. i'm such a newb
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";
	}
An if-else construct is far more natural for this.

But if we must use a switch-case instead, we can exploit the fact that true converted to an int is 1,
and false converted to an int is 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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.
Topic archived. No new replies allowed.