宏内语句内的逗号被误解为宏参数分隔符
我刚刚创建了一个 Xcode 项目并编写了以下代码:
#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 有两个参数而不是正确的参数。
那么,当我想在宏的语句中使用逗号时,我该怎么办?
这个 C++ 问题提出了一种在逗号周围放置一些圆括号 () 的方法,这显然导致预处理器意识到逗号不是宏参数分隔符。但我突然想到,我并没有想到在 Objective C 中做到这一点的方法。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在调用周围添加额外的括号是有效的:
Adding additional parentheses around the call works:
将其分开是可行的,但可能有更简单的方法
Separating it out works, but there might be a simpler way
尝试 NSString* string = foo([NSString stringWithFormat: (@"%d", n)]);
否则,试试卡特的方法,效果很好。
Try NSString* string = foo([NSString stringWithFormat: (@"%d", n)]);
Otherwise, try Carter's method, which works just fine.