在整数运算中计算商和余数时,使用无符号类型比较快。以下这段典型的代码是编译器产生的32位整型数除以4的代码:
不好的代码推荐的代码
编译前编译后
int i; mov eax, i
i = i / 4;cdq
and edx, 3 add eax, edx sar eax, 2 mov i, eax
编译前编译后
unsigned int i; shr i, 2
i = i / 4;
总结:
无符号类型用于:
除法和余数
循环计数
数组下标
有符号类型用于:
整型到浮点的转化
while VS. for
在编程中,我们常常需要用到无限循环,常用的两种方法是while (1) 和 for (;;)。这两种方法效果完全一样,但那一种更好呢?然我们看看它们编译后的代码:
编译前编译后
while (1); mov eax,1 test eax,eax
je foo+23h
jmp foo+18h
编译前编译后
for (;;);jmp foo+23h
一目了然,for (;;)指令少,不占用寄存器,而且没有判断跳转,比while (1)好。