How to use ellipsis in c's case statement?

岁酱吖の 提交于 2019-12-21 17:27:26

问题


CASE expr_no_commas ELLIPSIS expr_no_commas ':'

I saw such a rule in c's syntax rule,but when I try to reproduce it:

int test(float i)
{
switch(i)
{
  case 1.3:
    printf("hi");
}
}

It fails...


回答1:


OK, this involves a bit of guesswork on my part, but it would appear that you're talking about a gcc extension to C that allows one to specify ranges in switch cases.

The following compiles for me:

int test(int i)
{
  switch(i)
  {
  case 1 ... 3:
    printf("hi");
  }
}

Note the ... and also note that you can't switch on a float.




回答2:


This is not standard C, see 6.8.4.2:

The expression of each case label shall be an integer constant expression




回答3:


ELLIPSIS means ..., not .. The statement should be like:

#include <stdio.h>

int main() {
    int x;
    scanf("%d", &x);

    switch (x) {
       case 1 ... 100:
           printf("1 <= %d <= 100\n", x);
           break;
       case 101 ... 200:
           printf("101 <= %d <= 200\n", x);
           break;
       default:
            break;
    }

    return 0;    
}

BTW, this is a non-standard extension of gcc. In standard C99 I cannot find this syntax.



来源:https://stackoverflow.com/questions/5327896/how-to-use-ellipsis-in-cs-case-statement

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