将多行代码合并为一行代码的方法是什么?

huangapple go评论90阅读模式
英文:

How to combine multiple lines of code into one line of code?

问题

以下是代码部分的翻译:

DEMO((Demo []){
  {"Hello World"},
  {"Hello World"}
});

这是你所描述的代码部分的翻译。

英文:

The demo code is as follows:

#include <stdio.h>

#define DEMO(array) demo(array, sizeof(array) / sizeof(array[0]))

typedef struct Demo {
    const char *msg;
} Demo;

void demo(Demo list[], size_t list_size) {
    for (int i = 0; i < list_size; i++) {
        printf("%s\n", list[i].msg);
    }
}

int main() {
    Demo d[] = {
        {"Hello World"},
        {"Hello World"}
    };

    DEMO(d);
}

I want to merge the code in the main function, the way I imagine the merge is like this:

DEMO((Demo []){
  {"Hello World"},
  {"Hello World"}
});

I remember seeing this kind of syntactic sugar in an open source project once, but I can't remember which project it was.

答案1

得分: 1

DEMO(((Demo[]){{"Hello World"}, {"Hello World"}}));
英文:
    DEMO(((Demo[]){{"Hello World"},{"Hello World"}}));

答案2

得分: 1

你确实可以使用一个复合字面值参数来调用宏,但在宏的定义中,你应该更加小心,要在展开中的参数的所有实例周围加上括号,除非它们是函数参数:sizeof(array[0]) 对参数 (Demo[]){{"Hello World"}, {"Hello World"}} 会导致语法错误。

#include <stdio.h>

#define DEMO(array) demo(array, sizeof(array) / sizeof((array)[0]))

typedef struct Demo {
    const char *msg;
} Demo;

void demo(Demo list[], size_t list_size) {
    for (int i = 0; i < list_size; i++) {
        printf("%s\n", list[i].msg);
    }
}

int main() {
    DEMO((Demo[]){{"Hello World"}, {"Hello World"}});
}

根据上述定义,你仍然可以使用复合字面值调用宏,但必须加上括号以确保正确的评估:

DEMO( ( (Demo[]){ {"Hello World"}, {"Hello World"} } ) );
英文:

You can indeed invoke the macro with a compound literal argument, but you should be more careful in the macro definition to parenthesize all instances of its argument in the expansion, except as function arguments: sizeof(array[0]) causes a syntax error for the argument (Demo[]){{&quot;Hello World&quot;}, {&quot;Hello World&quot;}}

#include &lt;stdio.h&gt;

#define DEMO(array) demo(array, sizeof(array) / sizeof((array)[0]))

typedef struct Demo {
    const char *msg;
} Demo;

void demo(Demo list[], size_t list_size) {
    for (int i = 0; i &lt; list_size; i++) {
        printf(&quot;%s\n&quot;, list[i].msg);
    }
}

int main() {
    DEMO((Demo[]){{&quot;Hello World&quot;}, {&quot;Hello World&quot;}});
}

With the posted definition, you can still invoke the macro with the compound literal, but it must be parenthesized to ensure proper evaluation:

    DEMO( ( (Demo[]){ {&quot;Hello World&quot;}, {&quot;Hello World&quot;}} ) );

huangapple
  • 本文由 发表于 2023年2月18日 17:29:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定