使用switch条件语句需要注意的几点

1. 当满足条件的case中没有break,程序将依次执行其后的每种条件(包括default)直到遇到break跳出
int main()
{
    int n = 1;
    switch(n) {
    case 1:
        printf("--1--\n");
    default:
        printf("default\n");
    case 2:
        printf("--2--\n");
        break;
    case 3:
        printf("--3--\n");

    }

    return 0;
}

输出结果:
--1--
default
--2--


2. 当没有发现满足条件的case,程序将跳转到default,如果default没有break,程序将依次执行其后的每种条件,直到遇到break跳出
int main()
{
    int n = 4;
    switch(n) {
    case 1:
        printf("--1--\n");
    default:
        printf("default\n");
    case 2:
        printf("--2--\n");
    case 3:
        printf("--3--\n");

    }

    return 0;
}

输出结果:
default
--2--
--3--

猜你喜欢

转载自openwrt.iteye.com/blog/2224048