我不确定这是否只发生在Apple 的 LLVM Compiler 4.0 (XCode 4.4.1)上,但我注意到以下行为:
NSUInteger currentIndex = 0;
NSUInteger sideSize = 2;
// Method A
for (NSInteger i = currentIndex-sideSize; i < currentIndex+sideSize; i++)
{
printf("In the loop\n"); // WON'T be executed
}
// Method B
for (NSInteger i = (NSInteger)(currentIndex-sideSize); i < currentIndex+sideSize; i++)
{
printf("In the loop\n"); // WON'T be executed
}
// Method C
for (NSInteger i = (NSInteger)(currentIndex-sideSize); i < (NSInteger)(currentIndex+sideSize); i++)
{
printf("In the loop\n"); // WILL be executed
}
// Method D
NSInteger initialIndex = currentIndex-sideSize;
NSInteger finalIndex = currentIndex+sideSize;
for (NSInteger i = initialIndex; i < finalIndex; i++)
{
printf("In the loop\n"); // WILL be executed
}
方法 B 和方法 C 几乎相同,只是我们没有将加法运算符的结果显式转换为有符号值。
谁能解释发生了什么?