宏内语句内的逗号被误解为宏参数分隔符

发布于 2024-11-25 17:29:18 字数 694 浏览 0 评论 0原文

我刚刚创建了一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夜访吸血鬼 2024-12-02 17:29:18

在调用周围添加额外的括号是有效的:

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

Adding additional parentheses around the call works:

NSString* string = foo(([NSString stringWithFormat:@"%d",n]));
溺孤伤于心 2024-12-02 17:29:18

将其分开是可行的,但可能有更简单的方法

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

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

NSString* stringBefore = [NSString stringWithFormat:@"%d",n];
NSString* string = foo(stringBefore);
悸初 2024-12-02 17:29:18

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

否则,试试卡特的方法,效果很好。

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文