关于宏定义的安全性,下面为什么会输出- 1?

2016-06-12 22:54:08 +08:00
 zhongshaohua
#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))

int fun(void)
{
int array[] = {1, 2, 3, 4, 5};

if ((ARRAY_SIZE(array) - 2) > -1) {
/* xxx */
return 0;
}

return -1;
}
2299 次点击
所在节点    Linux
5 条回复
sen506
2016-06-12 23:28:13 +08:00
int 转成 uint 去运算了,,
azh7138m
2016-06-12 23:31:35 +08:00
楼上正解, sizeof 返回的是无符号数,运算符两边存在无符号数的时候就会把带符号数转换为无符号数
htfy96
2016-06-12 23:52:02 +08:00
因为 ARRAY_SIZE(array)-2 是 unsigned long ,比-1 的 int 阶高,所以 int 会被转成 unsigned long
zhongshaohua
2016-06-13 12:05:17 +08:00
感谢楼上各位老司机
liashui
2016-08-13 21:29:52 +08:00
If both operands have the same type, then no further conversion is needed.
Otherwise, if both operands have signed integer types or both have unsigned
integer types, the operand with the type of lesser integer conversion rank is
converted to the type of the operand with greater rank.
Otherwise, if the operand that has unsigned integer type has rank greater or
equal to the rank of the type of the other operand, then the operand with
signed integer type is converted to the type of the operand with unsigned
integer type.
Otherwise, if the type of the operand with signed integer type can represent
all of the values of the type of the operand with unsigned integer type, then
the operand with unsigned integer type is converted to the type of the
operand with signed integer type.
Otherwise, both operands are converted to the unsigned integer type
corresponding to the type of the operand with signed integer type.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/285226

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX