什么时候适合在符号常量/宏中包含类型转换,如下所示:
#define MIN_BUF_SIZE ((size_t) 256)
通过类型检查使其行为更像真实变量是一种好方法吗?
什么时候适合使用
L
orU
(orLL
) 后缀:#define NBULLETS 8U #define SEEK_TO 150L
4 回答
您需要在默认类型不合适的任何时候执行此操作。而已。
在不应用自动转换的地方键入常量可能很重要,特别是具有可变参数列表的函数
printf("my size is %zu\n", MIN_BUF_SIZE);
int
当和的宽度size_t
不同并且您不会进行演员表时,很容易崩溃。
但是你的宏还有改进的余地。我会这样做
#define MIN_BUF_SIZE ((size_t)+256U)
(看到那个小+
标志了吗?)
当这样给出时,宏仍然可以在预处理器表达式中使用(with #if
)。这是因为在预处理器中,(size_t)
计算0
结果也是无符号的256
。
Explicitly indicating the types in a constant was more relevant in Kernighan and Richie C (before ANSI/Standard C and its function prototypes came along).
Function prototypes like double fabs(double value);
now allow the compiler to generate proper type conversions when needed.
You still want to explicitly indicate the constant sizes in some cases. The examples that come to my mind right now are bit masks:
#define VALUE_1 ((short) -1)
might be 16 bits long while#define VALUE_2 ((char) -1)
might be 8. Therefore, given along x
,x & VALUE_1
andx & VALUE_2
would give very different results.- This would also be the case for the L or LL suffixes: the constants would use different numbers of bits.