Switch Function Errors?

Discussion in 'Mac Programming' started by Darkroom, Sep 9, 2008.

  1. Guest

    Darkroom

    Joined:
    Dec 15, 2006
    Location:
    Montréal, Canada
    #1
    so i'm studying beginner C but i've got mad problems with this switch function in xcode:

    New Project > Command Line Utility > Standard Tool

    Code:
    #include <stdio.h>
    
    main ()
    	{
    	int number;
    	printf("Make a choice (1 / 2 / 3): ");
    		do
    		{
    		scanf("%d", &number);
    		switch (number);	
    			{
    			case (1) : printf("You chose #1\n");
    			break;
    			case (2) : printf("You chose #2\n");
    			break;
    			case (3) : printf("You chose #3\n");
    			break;
    
    			default : printf("Invalid Choice (\"%d\").  Please Select Again.\n", number);
    			}
    		}
    		while ((number < 1) || (number > 3));
    	
    	return 0;
    	}
    
    the errors i'm receiving state "Case Label Not Within Switch Statement", but they totally are, aren't they?!

    i also get that weird warning "Return Type Defaults To Int" if i write "main()" instead of "int main()"...
     
  2. thread starter Guest

    Darkroom

    Joined:
    Dec 15, 2006
    Location:
    Montréal, Canada
    #2
    woops! forgot to remove that pesky comma here "switch (number);"

    ... dumb...
     
  3. macrumors newbie

    Joined:
    Sep 9, 2008
    Location:
    Natick, MA.
    #3
    I am also a beginner C programmer,

    and make mistakes like that all the time. One thing I noticed, other than the semicolon, is that you have parenthesis around your case numbers. I don't know if this would cause a problem, but I do know it would work without them.

    switch (number){
    case 1: printf(--------);
    break;
    case 2: printf(--------);

    etc...}

    Cheers!
     
  4. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #4
    Watch for this with your loops, too:
    Code:
    int x = 0;
    for(x = 0; x < 10; x++);
    {
      printf("X is: %d\n",x);
    }
    
    This is perfectly valid code, but the output will be:
    X is 10

    Not at all what you were hoping for.

    -Lee
     
  5. macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
    #5
    Actually, the output will be

    X is: 10

    (har har har)
     

Share This Page