1

I just created an Xcode project and wrote the following code:

#define foo(x) x
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    int n = 666;
    NSString* string = foo([NSString stringWithFormat: @"%d", n]);
    NSLog (@"string is %@", string);
    [self.window makeKeyAndVisible];
        return YES;
}

When I try to run this, I get a bunch of errors, because the preprocessor decides that that comma after the stringWithFormat: is supposed to be separating two macro arguments, therefore I have used foo with two arguments instead of the correct one.

So when I want a comma inside a statement inside my macro, what can I do?

This C++ question suggests a way to put some round parens () around the comma, which apparently leads the preprocessor to realize that the comma is not a macro argument separator. But off the top of my head, I'm not thinking of a way to do that in objective C.

Community
  • 1
  • 1
William Jockusch
  • 26,513
  • 49
  • 182
  • 323

3 Answers3

5

Adding additional parentheses around the call works:

NSString* string = foo(([NSString stringWithFormat:@"%d",n]));
Carter
  • 3,053
  • 1
  • 17
  • 22
0

Separating it out works, but there might be a simpler way

NSString* stringBefore = [NSString stringWithFormat:@"%d",n];
NSString* string = foo(stringBefore);
Carter
  • 3,053
  • 1
  • 17
  • 22
0

Try NSString* string = foo([NSString stringWithFormat: (@"%d", n)]);

Otherwise, try Carter's method, which works just fine.

spamboy
  • 32
  • 5