是否有一个C预处理程序宏可以打印出一个结构? [英] Is there a C preprocessor macro to print out a struct?

查看:73
本文介绍了是否有一个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.

这篇关于是否有一个C预处理程序宏可以打印出一个结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆