0

I have a macro that I stupidly set up when developing under AIX. It generates a 'trigger' value that I use in case switches. Like so:

#define TRIGGER_BUTTON(c) ((WIDGET_BUTTON << 16) | 'c')

meant to be used in a case switch, like so:

switch(GetTrigger()) {
case TRIGGER_BUTTON(A):    /* This constant sent by button A */
    break;
}

The AIX xlc compiler handled this fine, but gcc doesn't. Turns out it's not legal C, but I have tons of code that uses this macro. I could run a bulk sed script and change all that code to use a new macro that requires you to code it with the trigger character quoted, but I found a post here that seemed to suggest a portable solution.

#define TRIGGER_BUTTON(c) ((WIDGET_BUTTON << 16) | ##c[0])

This works, in the sense that both the AIX compiler and gcc accept it. But the problem is that the resulting expansion is not a valid integer constant, and so can't be used in a case switch. I guess it's producing code that actually puts together the combined integer value at run time from a constant string created from the macro argument - rather than producing a constant integer at compile time.

printf("%x\n", TRIGGER_BUTTON(A));

correctly prints 30041 (where WIDGET_BUTTON is defined as 3)

but the compiler spits out the case TRIGGER_BUTTON(A) as an invalid integer expression.

So, back to the drawing board - or my sed script, if I have to. Can anybody think of a way to stringize a non-quoted character and turn it into an integer constant?

Didn't think so... ;-)

But thanks anyway.

littlenoodles
  • 435
  • 4
  • 13
  • 1
    It's not very likely that you switched from AIX to Windows, but Microsoft offers the ["charizing operator"](https://msdn.microsoft.com/en-us/library/91tt6dfs.aspx) `#@` in analogy to the stringizing operator `#` as an extension. – M Oehm Apr 07 '16 at 16:03
  • 1
    `#define TRIGGER_BUTTON(c) ((3 << 16) | (""#c [0]))` should work. – mch Apr 07 '16 at 16:07
  • @alk yes: http://ideone.com/Gseu9A – mch Apr 07 '16 at 16:10
  • @mch: The OP says that it works, but the macro is used as a `switch` case constant, and it won't work there, because it's not an integer constant. – M Oehm Apr 07 '16 at 16:12
  • In your possible work around, you have `##`, which is the token pasting operator. I think you meant `#`, which is the quoting operator. – Adrian McCarthy Apr 07 '16 at 16:55
  • @MOehm something like that: http://ideone.com/2ME6f1 ? – mch Apr 08 '16 at 08:01
  • @mch: No, something like that: `switch (var) { case MACRO(A): ...}` – M Oehm Apr 08 '16 at 08:03

0 Answers0