views:

65

answers:

1

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  A: 

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)
rwong