英文:
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[]){{"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"}});
}
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[]){ {"Hello World"}, {"Hello World"}} ) );
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论