https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89408

            Bug ID: 89408
           Summary: No constant folding when dereferencing string literals
           Product: gcc
           Version: 8.1.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: jwerner at chromium dot org
  Target Milestone: ---

See the following minimal test case:

int main(int argc, char **argv)
{
        switch (argc) {
        case "C"[0]:
                return 1;
        }
}

When compiling this, GCC throws the error:

test.c: In function 'main':
test.c:6:2: error: case label does not reduce to an integer constant
  case "C"[0]:
  ^~~~

Obviously, since the string literal "C" is constant, it should be trivial to
reduce it to an integer constant, just as if I had written 'C'.

This may seem like a pointless construct, but it is useful when using token
stringification in macros (because the preprocessor doesn't allow you to
stringify directly to a character constant). For example, a macro that returns
the character keycode for the key combination Ctrl+X (for any Latin letter) can
be nicely written as:

#define CTRL(letter) (#letter[0] & 0x1f)

Unfortunately, this fails in switch statements due to the bug described here.
(When used in other contexts, looking through the disassembly shows that the
optimizer does in fact seem to be able to constant fold the whole expression at
some point.)

Reply via email to