Switch Statement-must case label always be constant?

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

  1. cybrscot macrumors 6502


    Dec 7, 2010
    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)

    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.

    #include <stdio.h>
    main ()
    	int velocity ;
    	printf ("Enter wind velocity (knots): ") ;
    	scanf ("%d", &velocity) ;
    	switch (velocity) {
    	case 1: printf ("Calm") ;
    	case 4: printf ("Light air") ;
    	case 28: printf ("Breeze") ;
    	case 48: printf ("Gale") ;
    	case 100: printf ("Hurricane") ;
    	return 0 ;
  2. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    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.

  3. balamw Moderator


    Staff Member

    Aug 16, 2005
    New England

Share This Page