如何在不使用sizeof运算符的情况下编写宏来打印任何整数数据类型的大小和范围。你能告诉我,怎么办? 提前谢谢。
答案 0 :(得分:1)
我认为以下宏可以帮助你。
#define RANGE(type, name) \
{ \
type min=0, max=0, bit=0; \
unsigned int bits=0; \
char *format; \
\
/* measure size of data type in bits */ \
bits=1; \
bit=1; \
while(bit <<= 1) bits++; \
\
/* signed or unsigned */ \
if((type)(1L << (bits-1)) > 0) \
{ \
format = "%lu"; /* unsigned */ \
min = 0; \
} \
else \
{ \
format = "%ld"; /* signed */ \
min = (type) (1L << (bits - 1)); \
} \
\
max = min - 1; /* roll over backwards */ \
printf("%s, %u bits : Range from ", name, bits); \
printf(format , (long)min); \
printf(" to "); \
printf(format , (long)max); \
printf("\n"); \
}
宏的参数是 1)任何整数数据类型 2)字符串格式的数据类型名称
例如
RANGE(unsigned int, "unsigned int");