1

With Clang, this code compiles fine, with no errors nor warnings:

static const int ZERO = 0;

int main() {
    switch (0) {
        case ZERO: break;
    }
}

But with GCC, I get an error:

<source>: In function 'main':
<source>:5:9: error: case label does not reduce to an integer constant
    5 |         case ZERO: break;
      |         ^~~~

Why is that?


Note: In this case I can just use a #define, but I'm wondering why there's a difference between Clang and GCC's behavior here.

I'm using Apple Clang 11.0.3 (seems to be installed via Xcode) and GCC 10.2.0, but I was able to reproduce this problem on Godbolt with Clang trunk and GCC trunk. Both locally and in Godbolt I was using x86-64.

Camelid
  • 1,535
  • 8
  • 21
  • 4
    It’s the difference between a constant integer and an integer constant. Clang is not following the C standard when it accepts the code. What compilation options are you using with each compiler? – Jonathan Leffler Feb 08 '21 at 04:32
  • I'm using the same options for both: `cc -xc -` (my `cc` is Clang) and `gcc-10 -xc -`. – Camelid Feb 08 '21 at 21:14
  • AFAIK, GCC 10 effectively uses `-std=gnu11` to compile when you don't specify otherwise. (I don't think it uses C18, not that it would make much difference.) I note that you've not identified which version of Clang you're using. It may be following a different standard. It may be using different GCC-compatibility assumptions. – Jonathan Leffler Feb 08 '21 at 21:39
  • @JonathanLeffler I have edited my question to include version information. – Camelid Feb 09 '21 at 20:04
  • There must be a diagnostic if you invoke the compiler in conforming mode (otherwise it is a compiler bug), e.g. use `-std=c11 -pedantic` (or whatever standard revision) – M.M Feb 09 '21 at 20:57

1 Answers1

0

This was in the sidebar:

switch case: error: case label does not reduce to an integer constant

Apparently 'const' in this case is not a constant expression, but a constant variable... well, just read the post. Seems like clang has different rules. Another reason why it is always good to compile on more than one compiler.

PeterT
  • 920
  • 8
  • 20
  • 1
    I also saw https://stackoverflow.com/questions/1712711/why-doesnt-gcc-allow-a-const-int-as-a-case-expression in the sidebar, but I would like to hear more about *why* there is a difference in behavior — it seems weird that GCC refuses to compile at all, while Clang doesn't even give a warning. – Camelid Feb 08 '21 at 03:30
  • 1
    @Camelid Turning up the warnings (or errors with `-Werror`) in Clang also causes it not to be accepted, saying that it's a GNU extension. – Thomas Jager Feb 08 '21 at 03:41
  • @Camelid Good point. Now I'd like to know why the difference too. – PeterT Feb 08 '21 at 23:58
  • @ThomasJager I am not able to reproduce what you are describing. What flags are you passing and to which version of Clang? – Camelid Feb 09 '21 at 20:12