Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

c - Switch statement not doing what I expect

What is wrong with this code:

switch (n)
{
    case 0:   strcpy(resultString, "Zero");
    case 1:   strcpy(resultString, "One");
    case 2:   strcpy(resultString, "Two");
    case 3:   strcpy(resultString, "Three");
    case 4:   strcpy(resultString, "Four");
    case 5:   strcpy(resultString, "Five");
    case 6:   strcpy(resultString, "Six");
    case 7:   strcpy(resultString, "Seven");
    case 8:   strcpy(resultString, "Eight");
    case 9:   strcpy(resultString, "Nine");
}
printf("%s", resultString);

It always prints "Nine" no matter the value of n. What am I doing wrong??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...