Using macros for string concatenation

208 Views Asked by At

I want to create macro that receives 2 arguments: NSString and ObjCBool and returns NSString.

I'm not familiar a lot with macros, anyway this is what I did so far:

#define fooOne(url)\
          @"1111111" url

 #define fooTwo(url)\
          @"2222222" url


#define root(url, flag)\
   if(!flag)fooOne(url)\
   else fooTwo(url)

Here I have 2 problems:

1) when I call fooOne as:

NSString *url = @"zzz";
NSLog(@"%@", fooOne(url)); 
// expected log should be: "1111111 zzz"

I get error: Expected ')'

2) When I call root(url, flag) as:

BOOL flag = YES;
NSString *url = @"zzz";
NSLog(@"%@", root(url, flag)); 
// expected log should be: "2222222 zzz"

I get an error: Expected expression

please help,

1

There are 1 best solutions below

3
Itai Ferber On BEST ANSWER

Compile-time string concatenation only works with string literals. At compile time @"hello, " @"world" is combined into a new string literal @"hello, world". This doesn't work with strings contained in variables — @"blabla" url is not a valid expression, even if url contains a string literal at runtime. You would have to call your macros with the literal inside: fooOne(@"zzz"), which would expand to @"blabla" @"zzz".

If you want to combine strings at runtime, you'll need to use +[NSString stringWithFormat:], or append the strings.