PDA

View Full Version : Switch Function Errors?




Darkroom
Sep 9, 2008, 07:08 AM
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


#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()"...



Darkroom
Sep 9, 2008, 07:14 AM
woops! forgot to remove that pesky comma here "switch (number);"

... dumb...

Muster Mark
Sep 9, 2008, 12:57 PM
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!

lee1210
Sep 9, 2008, 01:52 PM
Watch for this with your loops, too:

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

toddburch
Sep 9, 2008, 02:33 PM
This is perfectly valid code, but the output will be:
X is 10


Actually, the output will be

X is: 10

(har har har)