繁体   English   中英

不懂带开关块程序的output

[英]Don't understand the output of program with a switch block

我想了解此代码的 output,特别是 output 的最后两行(第 4 行和第 5 行)。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    double x = 2.1;

    while (x * x <= 50) {
        switch ((int) x) {
            case 6:
                x--;
                printf("case 6, x= %f\n ", x);

            case 5:
                printf("case 5, x=%f\n ", x);

            case 4:
                printf("case 4, x=%f\n ", x);
                break;

            default:
                printf("something else, x=%f\n ", x);
        }

        x +=2;
    }

    return 0;
}

如果没有 break 语句,一个 case 结尾的代码将落入下一个 case 的代码中。

因此,当x达到值 6.1 时,由于x*x仍然小于 50,因此您点击case 6 ,并且没有 break 语句,您还输入了case 5case 4代码。 因此,值 5.1(递减x的结果)被打印 3 次。

这是一个很好的机会来强调您应该在启用所有警告的情况下编译您的代码。 使用gcc -W -Wall ,您的程序将生成以下警告:

 .code.tio.c: In function 'main': .code.tio.c:12:17: warning: this statement may fall through [-Wimplicit-fallthrough=] printf("case 6, x= %f\n ", x); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~.code.tio.c:14:13: note: here case 5: ^~~~.code.tio.c:15:17: warning: this statement may fall through [-Wimplicit-fallthrough=] printf("case 5, x=%f\n ", x); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~.code.tio.c:17:13: note: here case 4: ^~~~

如果您的代码有意进入下一个案例, gcc将遵循注释该意图的注释。 然后不会发出警告。

    switch ((int) x) {
        case 6:
            x--;
            printf("case 6, x= %f\n ", x);
            // FALLTHROUGH
        case 5:
            printf("case 5, x=%f\n ", x);
            // FALLTHROUGH
        case 4:
            printf("case 4, x=%f\n ", x);
            break;

        default:
            printf("something else, x=%f\n ", x);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM