Are triple dots inside a case (case '0' … '9':) valid C language switch syntax? [duplicate]

微笑、不失礼 提交于 2020-01-29 10:23:22

问题


I noticed this in open source code files for DRBD software (user/drbdtool_common.c)

const char* shell_escape(const char* s)
{
    /* ugly static buffer. so what. */
    static char buffer[1024];
    char *c = buffer;

    if (s == NULL)
        return s;

    while (*s) {
        if (buffer + sizeof(buffer) < c+2)
            break;

        switch(*s) {
        /* set of 'clean' characters */
        case '%': case '+': case '-': case '.': case '/':
        case '0' ... '9':
        case ':': case '=': case '@':
        case 'A' ... 'Z':
        case '_':
        case 'a' ... 'z':
            break;
        /* escape everything else */
        default:
            *c++ = '\\';
        }
        *c++ = *s++;
    }
    *c = '\0';
    return buffer;
}

I have never seen this "triple dot" construction (case '0' ... '9':) in C before. Is it a valid standard C language? Or is that some kind of preprocessor magic? What's going on here?


回答1:


As others have said, this is a compiler-specific extension. Invoke the compiler with the right options (say, gcc -std=c99 -pedantic), and it should warn you about it.

I'll also point out that its use is potentially dangerous, apart from the fact that another compiler might not implement it. 'a' ... 'z' denotes the 26 lowercase letters -- but the C Standard doesn't guarantee that their values are contiguous. In EBCDIC, for example, there are punctuation characters among the letters.

On the other hand, I doubt that either gcc or Sun C supports systems that use a character set in which the letters aren't contiguous. (They are in ASCII and all its derivatives, including Latin-1, Windows-1252, and Unicode.)

On the other other hand, it excludes accented letters. (Depending on how DRBD is used, that may or may not be an issue.)




回答2:


That's a non-standard language extension.

Probably GCC: http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Case-Ranges.html.




回答3:


No, this is an extension of GCC.




回答4:


This is not standard C, but is an extension found in the Sun C compiler.

Refer to: 2.7 Case Ranges in Switch Statements at Oracle's web site.

UPDATE: Apparently, not just Oracle! :-)



来源:https://stackoverflow.com/questions/7043788/are-triple-dots-inside-a-case-case-0-9-valid-c-language-switch-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!