case 语句中的省略号是标准 C/C++

发布于 2024-11-06 01:29:47 字数 606 浏览 1 评论 0原文

我正在浏览 Linux 内核中的一些代码,遇到了类似 case '0' ... '9': 的语句

。为了尝试这个,我创建了下面的测试程序。

#include <iostream>

int main()
{
    const int k = 15;

    switch (k)
    {
    case 0 ... 10:
        std::cout << "k is less than 10" << std::endl;
        break;
    case 11 ... 100:
        std::cout << "k is between 11 and 100" << std::endl;
        break;
    default:    
        std::cout << "k greater than 100" << std::endl;
        break;
    }
}   

上面的程序确实可以编译,尽管我以前从未在 case 语句构造中遇到过省略号。这是标准的 C 和 C++ 还是 GNU 对该语言的特定扩展?

I was browsing some code in the linux kernel and I came across the statements like case '0' ... '9':

To try this out I created the test program below.

#include <iostream>

int main()
{
    const int k = 15;

    switch (k)
    {
    case 0 ... 10:
        std::cout << "k is less than 10" << std::endl;
        break;
    case 11 ... 100:
        std::cout << "k is between 11 and 100" << std::endl;
        break;
    default:    
        std::cout << "k greater than 100" << std::endl;
        break;
    }
}   

The program above does compile although I have never come across the elipses in case statement construct before. Is this standard C and C++ or is this a GNU specific extension to the language?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

半枫 2024-11-13 01:29:47

这是 GNU C 编译器的 case range 扩展,它不是标准 C 或 C++。

That is the case range extension of the GNU C compiler, it is not standard C or C++.

丑疤怪 2024-11-13 01:29:47

那是一个扩展。使用 -pedantic 编译程序会给出:

example.cpp: In function ‘int main()’:
example.cpp:9: error: range expressions in switch statements are non-standard
example.cpp:12: error: range expressions in switch statements are non-standard

clang 给出更好的警告:

example.cpp:9:12: warning: use of GNU case range extension [-Wgnu]
    case 0 ... 10:
           ^
example.cpp:12:13: warning: use of GNU case range extension [-Wgnu]
    case 11 ... 100:
            ^

That's an extension. Compiling your program with -pedantic gives:

example.cpp: In function ‘int main()’:
example.cpp:9: error: range expressions in switch statements are non-standard
example.cpp:12: error: range expressions in switch statements are non-standard

clang gives even better warnings:

example.cpp:9:12: warning: use of GNU case range extension [-Wgnu]
    case 0 ... 10:
           ^
example.cpp:12:13: warning: use of GNU case range extension [-Wgnu]
    case 11 ... 100:
            ^
深巷少女 2024-11-13 01:29:47

这是 GCC 对 C 的扩展,在 这个答案中提到 基本上是一个重复的问题,并确认在 GCC 文档中

This is a GCC extension to C, mentioned in this answer to what is basically a duplicate question, and confirmed in the GCC documentation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文