What is wrong with this code:
switch (n)
{
case 0: strcpy(resultString, \"Zero\");
case 1: strcpy(resultString, \"One\");
case 2: strcpy(re
You need to break after each case.
case 0:
do soemthing;
break;
case 1:
do something;
break;
In many managed languages, it won't let "one case fall through to another," and throws an error. But C loves to let you do whatever you want!
You need a break statement at the end of each case. Otherwise control falls straight through to the next case.
Change your code to:
switch (n)
{
case 0: strcpy(resultString, "Zero");
break;
case 1: strcpy(resultString, "One");
break;
case 2: strcpy(resultString, "Two");
break;
case 3: strcpy(resultString, "Three");
break;
case 4: strcpy(resultString, "Four");
break;
case 5: strcpy(resultString, "Five");
break;
case 6: strcpy(resultString, "Six");
break;
case 7: strcpy(resultString, "Seven");
break;
case 8: strcpy(resultString, "Eight");
break;
case 9: strcpy(resultString, "Nine");
break;
}
printf("%s", resultString);
You can find the switch statement documented here or in any book on the C language.
From the standard :
6.4.2 The switch statement [stmt.switch]
case and default labels in themselves do not alter the flow of control, which continues unimpeded across such labels. To exit from a
switch
, seebreak
(6.6.1).6.6.1 The break statement [stmt.break]
The
break
statement shall occur only in an iteration-statement or aswitch
statement and causes termination of the smallest enclosing iteration-statement or switch statement; control passes to the statement following the terminated statement, if any.
That means that is you don't use break
after each case
, you program will enter in the first case
who matches the condition and will continue executing every line of the switch
until the end.
You should just do something like :
switch( n )
{
case 0:
// ...
break; // <- Note the break
//...
default:
// ...
}
You missed break;
after each case
Example :
case 0: strcpy(resultString, "Zero");break;
..
..
case 8: .... ; break;
..