-2

Is there anyway to token paste a parameter or non-function macro at the BEGINNING of the macro definition? In other words, just as if something like #define JOIN_TOKENS(a, b) ##a##b were allowed.

An example would be JOIN_TOKENS(Up, Here) turning into UpHere. Also, I'd like for any values passed as parameters to not be expanded. This almost did it, but it produces an error:

#define APPEND_TOKEN(a, b) a##b
#define VAR 0
#define JOIN(a, b) APPEND_TOKEN(##a, ##b)
JOIN(VAR, iable)

It was supposed to produce VARiable, and it did, but there were accompanying errors:

<stdin>:4:1: error: pasting formed '(VAR', an invalid preprocessing token
JOIN(VAR, iable)
^
<stdin>:3:33: note: expanded from macro 'JOIN'
#define JOIN(a, b) APPEND_TOKEN(##a, ##b)
                                ^
<stdin>:4:1: error: pasting formed ',iable', an invalid preprocessing token
<stdin>:3:38: note: expanded from macro 'JOIN'
#define JOIN(a, b) APPEND_TOKEN(##a, ##b)
                                     ^
/



VARiable
2 errors generated.
Melab
  • 2,594
  • 7
  • 30
  • 51

2 Answers2

2

Something like that?

//encloses the argument Arg in quotation marks
#define STRINGIFY(Arg) STRINGIFY_(Arg)
#define STRINGIFY_(Arg) #Arg

//concatenates the two arguments Arg1 and Arg2 to a new token
#define CAT(Arg1, Arg2) CAT_(Arg1, Arg2)
#define CAT_(Arg1, Arg2) Arg1##Arg2

Test:

#define A MY_
#define B SPECIAL_
#define C TYPE

printf("%s\n", STRINGIFY(CAT(A, CAT(B, C))));
//output: MY_SPECIAL_TYPE

/* or */

#define MY_VAR CAT(A, CAT(B, C))
typedef int MY_VAR;

MY_VAR i = 42;

printf("%d\n", i);
//output: 42
Erdal Küçük
  • 4,810
  • 1
  • 6
  • 11
0
#define APPEND_TOKEN(a, b) a##b
#define VAR 0
#define JOIN(a, b) APPEND_TOKEN(##a, ##b)
JOIN(VAR, iable)

It was supposed to produce VARiable

Just use the following code:

#define VAR 0
#define JOIN(a, b)   a##b
JOIN(VAR, iable)

Produces the following preprocessor output. Tested on godbolt:

VARiable
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • 1
    That doesn't work when `VAR` is a macro. I mentioned token pasting specifically, so I do not want `a` expanded, just as `b` would not be expanded. – Melab Sep 19 '21 at 23:00
  • It does work when VAR is a macro. I do not understand. Edited the answer with an online link. Macro arguments as part of `##` are not rescanned for further replacement. – KamilCuk Sep 19 '21 at 23:09
  • 1
    Sorry. You are right. I was thinking of a set of macros that I thought were similar enough to yours. – Melab Sep 19 '21 at 23:18
  • Now what if you wanted `VAR` to expand? – Melab Sep 19 '21 at 23:32
  • Then see `CAT` from the other answer.... – KamilCuk Sep 20 '21 at 07:10