在C++中,有
#define DEBUG(A) cerr << (A) << endl;
我可以发送任何东西,它可以打印出来.但是,在C中,我必须用%d,%c或%s等指定它的类型.但我不想一直写它的类型,我想使用fprintf像cerr.我怎样才能做到这一点?
例如:在C中
#define DEBUG(A) X // X is what I want to write 
...
// in function, when I put
DEBUG(5);          // I just want to print 5 
// or, with same statement, when I say 
DEBUG('a');        // output : a
eti*_*ici 30
您可以使用GNU C语言扩展:
#define DEBUG(x)                                                 \
  ({                                                             \
    if (__builtin_types_compatible_p (typeof (x), int))          \
        fprintf(stderr,"%d\n",x);                                \
    else if (__builtin_types_compatible_p (typeof (x), char))    \
        fprintf(stderr,"%c\n",x);                                \
    else if (__builtin_types_compatible_p (typeof (x), char[]))  \
        fprintf(stderr,"%s\n",x);                                \
    else                                                         \
        fprintf(stderr,"unknown type\n");                        \
  })
这些很好:
DEBUG("hello"); //prints hello
DEBUG(11110);   //prints 11110 
但对于字符,你应该使用左值,否则它的类型将是"int":
char c='A';
DEBUG(c);    // prints A
DEBUG('A');  // prints 65
Dav*_*nan 14
你不能fprintf()以你想要的方式使用.欢迎来到C.
C++ I/O流运算符是类型安全的,并使用运算符重载来实现它们的魔力.这在C中不可用,因此您必须坚持使用不安全的格式字符串方法.
Lin*_*cer 10
原则上,你不能,因为C没有重载机制.
但是,您可以定义许多宏,例如:
#define DEBUG_INT(x)  fprintf(stderr, "%d\n", (x))
#define DEBUG_CHAR(x) fprintf(stderr, "%c\n", (x))
没有办法摆脱转换规范,但如果你有一个C99编译器,你可以使用__VA_ARGS__并使它更容易,例如,
#include <stdio.h>
#define DEBUG(fmt, ...) fprintf(stderr, (fmt), __VA_ARGS__)
int main(void) {
  int foo = 42;
  char *t = "foobar";
  DEBUG("%s:%d\n", t, foo);
  return 0;
}