Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

cybrscot

macrumors 6502
Original poster
Dec 7, 2010
282
0
Somewhere in Southeast Asia
Okay, I have written the below code (pasted at bottom)(switch statement) because i was having trouble writing the code in the "if..else" style. I will post that code on a different thread. But I wanted to see if I could accomplish the same thing in a different way.

The code below asks a user to enter wind velocity, then the program will output the condition, such as calm, gale, hurricane, etc. However, because the switch statement says that the case label must be in "case constant-expression: statement" form. It required that the user input exactly one of the cases exactly, but I really would like to specify a range. Can I do that somehow with a switch?

I'd like (and I tried) something like
case < 1 printf (statement, calm)
break; /*dont pay attention to the stmt, ex. only
case < 28 printf (statement, gale)
break;

but it doesn't work of course because it's not constant,

Here is my copy/pasted code..... the code compiles and works, but I want to allow the user to enter any number, and my switch statement to be able to break and output the correct conditions.

Code:
#include <stdio.h>

main ()

{

	int velocity ;

	printf ("Enter wind velocity (knots): ") ;
	scanf ("%d", &velocity) ;
	
	switch (velocity) {
	
	case 1: printf ("Calm") ;
			  break;
	case 4: printf ("Light air") ;
			  break;
	case 28: printf ("Breeze") ;
			   break;
	case 48: printf ("Gale") ;
				break;
	case 100: printf ("Hurricane") ;
				break;
	}
	return 0 ;
	
}
 
The cases must be constant. There's no way around it. It sounds like this is a case where elseif is the right way to go. You could have the cases be enum values, and set the variable in the switch to one of these, but you'd be setting it in an if-elseif-else style structure anyway, so it's not getting you out of that.

-Lee
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.