宏中的语句内的逗号被误解为宏参数分隔符 [英] Comma inside a statement inside a macro being misinterpreted as a macro argument separator

查看:137
本文介绍了宏中的语句内的逗号被误解为宏参数分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚创建了一个Xcode项目,并编写了以下代码:

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;
}

当我尝试运行此命令时,我遇到了很多错误,因为预处理程序确定stringWithFormat:之后的逗号应该分隔两个宏参数,因此我将foo与两个参数一起使用,而不是正确的参数

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?

此C ++问题提出了一种放置圆角括号的方法()围绕逗号,这显然使预处理器意识到逗号不是宏参数分隔符.但是,从我的头顶上,我没有想到在目标C中做到这一点的方法.

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]));

这篇关于宏中的语句内的逗号被误解为宏参数分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆