开发者

How to use ellipsis in c's case statement?

CASE expr_no_commas ELLIPSIS expr_no_commas ':'

I saw such a rule in c's syntax rule,but when I t开发者_运维百科ry to reproduce it:

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

It fails...


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.


This is not standard C, see 6.8.4.2:

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜