2

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!

OTZ
  • 3,003
  • 4
  • 29
  • 41
  • Is this a contest or what? Where is the question? – Jens Gustedt Aug 26 '10 at 08:24
  • You paste your own PRINT macro which, given a variable and perhaps a string format and other needed information, stringifies the variable value and print it out. – OTZ Aug 27 '10 at 03:47

1 Answers1

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)
rwong
  • 6,062
  • 1
  • 23
  • 51