C专家编程_1.10

C专家编程_1.10

一个微妙的bug
(强制类型转换)

int array[ ] = { 23,  34,  12,  17, 204,  99,  16 };
#define TOTAL_ELEMENTS  ( sizeof (array) / sizeof(array[0]) )
main()
{
	int d = -1,   x;
	/* ... ... */
	if( d <= TOTAL_ELEMENTS -2 )
		x = array[d+1];
	/* ... ... */
}

if 语句在signed 和unsigned int 直接测试相等性,(sizeof()为unsigned int类型)所以d被升级为unsigned int 类型。而-1转换unsigned int为一个巨大的正整数,致使表达式的值为假。

猜你喜欢

转载自blog.csdn.net/Old_Zero/article/details/88086988