-4

我想了解这段代码的输出,特别是输出的最后两行(第 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;
}
4

1 回答 1

1

Without a break statement, the code at the end of one case will fall through into the code of the next case.

So, when x reaches the value 6.1, since x*x is still less than 50, you hit case 6, and with no break statement, you also enter the case 5 and case 4 code. So, the value 5.1 (the result of decrementing x) is printed 3 times.

This is a good opportunity to stress that you should compile your code with all warnings enabled. With gcc -W -Wall, your program will generate the following warnings:

.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:
             ^~~~

If your code is intentionally wanting to fall-through to the next case, gcc will honor a comment annotating that intent. The warning will then not be emitted.

    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);
于 2019-11-06T21:49:19.433 回答