如何通过c工作案件堕落?

时间:2016-01-20 15:27:17

标签: c switch-statement

#include <stdio.h>

main() /* count digits, white space, others */
{
    int c, i, nwhite, nother, ndigit[10];
    nwhite = nother = 0;
    for (i = 0; i < 10; i++)
        ndigit[i] = 0;
    while ((c = getchar()) != EOF) {
        switch (c) {
        case '0': case '1': case '2': case '3': case '4':
        case '5': case '6': case '7': case '8': case '9':
            ndigit[c-'0']++;
            break;
        case ' ':
        case '\n':
        case '\t':
            nwhite++;
            break;
        default:
            nother++;
            break;
        }
    }
    printf("digits =");
    for (i = 0; i < 10; i++)
        printf(" %d", ndigit[i]);
    printf(", white space = %d, other = %d\n",
        nwhite, nother);
    return 0;
}

问题1 - 如果c = 0,这些情况如何起作用然后控制直接转到语句并中断或者是否记得c = 0并继续直到语句?

#include <stdio.h>

int main()
{
    int i = 0;
    for(i = 0; i < 20; i++)
    {
        switch(i)
        {
            case 0: i+=5;
            case 1: i+=2;
            case 5: i+=5;
            default: i+= 4;
            break;
        }
        printf("%d ", i);
    }
    return 0;
} 

问题2 - 在这样的程序中,为什么2在案例1中加起来? i的当前值是5?如果一个case为真,控件是否会忽略所有剩余/下属情况常量表达式,直到找到中断为止?

1 个答案:

答案 0 :(得分:0)

c中的开关跳转到具有匹配值的情况,然后从那里执行所有代码,直到找到中断或交换结束。在第二个例子中,对于值0的儿子,所有其他情况也被评估。如果你不想要这个,你需要休息一下。