-
Switch/case problem
I've made a code to recognize a number and then declare a matching course.
But it appears that this code sucks because i get 32 errors.
Must be some sort of record......
Code:
char* course_check(int course)
{
switch(course)
{
case 1:
char courseString[]="Maths";
break;
case 2:
char courseString[]="English";
break;
case 3:
char courseString[]="Deutch";
break;
case 4:
char courseString[]="French";
break;
case 5:
char courseString[]="German";
break;
case 6:
char courseString[]="Geography";
break;
case 7:
char courseString[]="History";
break;
else:
char courseString[]="No Course";
}
char* p=&courseString; .
return *p;
}
-
Correct me if im wrong but in the end of a switch statements its a default case not an else case. It should be
Code:
Default:
char courseString[]="No Course";
}
Also i dont know if this was when you were entering your code, but theres a period in the end of one of yoru lines
Code:
char* p=&courseString; .
Should be:
Code:
char* p=&courseString;
One more thing. If woudl help to make your codes consistent when indenting so that it's easier to read. You have breaks all over the sides and its hard to figure out erros like that.
-
A switch does not comprise of if/else.
Code:
case 7: { char courseString[]="History";
break; }
default : { char courseString[]="No Course";
break; }
}
Kuphryn
-
What about removing the switch and use an array?
Code:
const char * course_check(int course)
{
static const char *courseString[] = {
"No Course", "Maths", "English", "Deutch",
"French", "German", "Geography", "History" };
if(course < 0 || course > 7)
course = 0;
return courseString[course];
}
-
Also, courseString goes out of scope when exiting the switch statement. You have to declare it before, or something.
I'm not even sure you can declare variables inside a switch due to the fact that the program flow can go through several cases:
Code:
switch(NrOfAdds)
{
case ThreeAdds:
Myvar++;
case TwoAdds:
Myvar++;
case OneAdd:
Myvar++;
break;
default:
break;
}
In the code below, it's not certain that MyVar is defined or not:
Code:
switch(Something)
{
case A:
int Myvar;
case B:
MyVar = 4;
break;
default:
break;
}