是否有一个C预处理程序宏可以打印出一个结构?

问题描述:

据我所知,无法在 C 中打印出结构值。

As far as I can tell, there's no way to print out a struct value in C.

即,这不会飞:

typedef struct {
    int a;
    double b;
} stype

stype a;

a.a=3;
a.b=3.4;

printf("%z", a);

相反,您必须说:

printf("a: %d\n", a.a);
printf("b: %f\n", a.b);

这似乎是一个完美的地方,您可以使用宏为任意保存大量的输入

This seems like a perfect place where you could use a macro to save a vast amount of typing for arbitrary structs.

C 预处理器的功能足以执行此转换吗?

Is the C preprocessor powerful enough to perform this transformation?

我认为最简单的解决方案(也许是最漂亮的解决方案)是使用函数来打印您的特定结构。

I think that the simplest solution (and maybe the most beautiful) is to use a function to print your specific struct.

void display_stype(stype *s)
{
    printf("a: %d\n", s->a);
    printf("b: %f\n", s->b);
}

如果更改了结构,则可以轻松地将代码放在一个地方。

If your struct changed, you can adapt in one place your code easily.