Your most general C macro for printing variable values in different types

谁都会走 提交于 2019-12-22 16:36:14

问题


Please share with us your favorite, and most general, PRINT or DEBUG macro applicable to all (or almost all) variables in different types and to arrays in C. The macro can have any number of parameters (though 1-3 are preferred); if it increases descriptive power at all, C99 features can be assumed.

#define PRINT(var, ...) \
   ...

Let's begin!


回答1:


For C++, template function can be much more powerful than macro.

template <typename T>
std::string tostring(const T& t);

The drawback of template argument is that it cannot distinguish between typedef aliases:

typedef LONG HRESULT;

For C, I think there is nothing you can do, without changing your structs. If you have control over the struct definitions, here are two tricks:

Add a field to the beginning of the struct, and set the field to a value that uniquely identifies the type of the structure, which can be used by the tostring function to choose the appropriate printing code.

typedef struct abcde
{
    int unique_struct_type_id; // assign this to a number that represents "abcde"
};

A similar method is to pass in a function pointer for printing the struct.

struct abcde
{
    void (*print_fn) (abcde* p);  // assign this to the printing function for "abcde"
}
#define PRINT_STRUCT(s) s->print_fn(s)


来源:https://stackoverflow.com/questions/3572391/your-most-general-c-macro-for-printing-variable-values-in-different-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!