Reputation: 417
I'm trying to concatenate two values each defined as macro. At this moment I've:
#define VAL1 @"im/"
#define VAL2 @"test"
#define GLUE_IN(x,y) (x ## y)
#define GLUE(x,y) GLUE_IN(x,y)
when I use it in code:
[array addObject:GLUE(VAL1, VAL2)];
it produces me an error: Pasting formed '"im/"@', an invalid preprocessing token
I'm aware that it may be solved by:
#define GLUE(x,y) [NSString stringWithFormat:@"%@%@",x,y]
however I'm curious is it possible to achieve this same result using preprocessor?
Upvotes: 0
Views: 1195
Reputation: 641
I'm not gonna ask why you ever need it, but here is possible solution:
#define VAL1 im
#define VAL2 test
#define STR2(x) #x
#define STR(x) STR2(x)
#define GLUE_IN(a,b) a##b
#define GLUE(x,y) GLUE_IN(x,y)
…
NSString *val1 = @(STR(GLUE(VAL1, VAL2)));
NSString *val2 = @"another " @"test";
NSLog(@"%@, %@", val1, val2);
It gives you
imtest, anothertest
However, you'll have some troubles with a slash sign. If I were you, I'd prefer another way.
Upvotes: 0
Reputation: 180917
##
concatenates tokens, not strings, which causes an invalid resulting token, and in this case is entirely un-necessary since @"im/" @"test"
- being compile time string constants - will be appended anyway. Just do;
#define GLUE_IN(x,y) (x y)
...which will result in
[array addObject:@"im/" @"test"]
...and things should work well.
Upvotes: 2