开发者

Comma inside a statement inside a macro being misinterpreted as a macro argument separator

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开发者_Go百科 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.


Adding additional parentheses around the call works:

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


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

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


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜