Switch Statement-must case label always be constant?

Discussion in 'Mac Programming' started by cybrscot, Jan 21, 2011.

  1. cybrscot macrumors 6502

    cybrscot

    Joined:
    Dec 7, 2010
    Location:
    Somewhere in Southeast Asia
    #1
    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 ;
    	
    }	
    	
     
  2. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    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
     
  3. balamw Moderator

    balamw

    Staff Member

    Joined:
    Aug 16, 2005
    Location:
    New England
    #3

Share This Page