记录C/C++中易混淆生僻的编程语法
1.
int i = 0xAA;
i ^= 0x0F - 0x0F; // 相当于:i ^= (0x0F - 0x0F);,计算得:i=0xAA
// 若是(i ^= 0x0F) - 0x0F;,计算得150
2.
long long m = 0x10000;
int n = 0x10000;
// 计算中间临时结果为8Byte,没溢出
double r1 = m * n; // r1 = 0x100000000;
long long r2 = m * n; // r2 = 0x100000000; sizeof(long long) = 8
int m = 0x10000;
int n = 0x10000;
// 计算中间临时结果默认为4Byte,导致溢出。
double r1 = m * n; // r1 = 0;
long long r2 = m * n; // r2 = 0;
char c1 = 0x70;
char c2 = 0x70;
// 计算中间临时结果默认为4Byte,没溢出。
int cc = c1 * c2; // cc = 0x3100
3. 移位操作符(左移<<或右移>>)的操作数必须是整数。取余运算符(%)的操作数必须是整数。
int i1 = 0x1000;
int i2 = -0x1000;
int i3 = 0x1000;
int i4 = -0x1000;
while (1)
{
i1 = i1 << 1; // 溢出先变为最大负值,再变为0
i2 = i2 << 1; // 溢出变为0
i3 = i3 >> 1; // 溢出后为0
i4 = i4 >> 1; // 溢出后为-1,一直是-1
}
int i2 = -0x1000;
int i3 = 0x1000;
int i4 = -0x1000;
while (1)
{
i1 = i1 << 1; // 溢出先变为最大负值,再变为0
i2 = i2 << 1; // 溢出变为0
i3 = i3 >> 1; // 溢出后为0
i4 = i4 >> 1; // 溢出后为-1,一直是-1
}
4. Int最大最小值 :
#include <stdio.h>
int main()
{
printf("max int = %d ", int( (unsigned int)(~0) >> 1) );
printf("min int = %d ", int(~((unsigned int)(~0) >> 1)) );
}
int main()
{
printf("max int = %d ", int( (unsigned int)(~0) >> 1) );
printf("min int = %d ", int(~((unsigned int)(~0) >> 1)) );
}
5. 数组指针.
char a[10] = {0};
int len = sizeof(a); // len = 10
a ++; // 错误,a为常量
a ++; // 错误,a为常量