基本数据类型的长度
C++中的基本数据类型长度跟编译环境有关。
https://www.tutorialspoint.com/cplusplus/cpp_data_types.htm
https://www.w3cschool.cn/cpp/cpp-data-types.html
自己在64位的win10上试了一下:
int main()
{
cout << "size of char:" << sizeof(char) << endl;
cout << "size of int:" << sizeof(int) << endl;
cout << "size of short int:" << sizeof(short int) << endl;
cout << "size of unsigned int:" << sizeof(unsigned int) << endl;
cout << "size of long int:" << sizeof(long int) << endl;
cout << "size of long:" << sizeof(long) << endl;
cout << "size of long long:" << sizeof(long long) << endl;
cout << "size of float:" << sizeof(float) << endl;
cout << "size of double:" << sizeof(double) << endl;
cout << "size of long double:" << sizeof(long double) << endl;
return 0;
}
基本数据类型之间的转换
- 短类型赋值给长类型时,会发生自动转换,合法;
- 非bool类型的值赋值给bool类型:0->false; 非0->true;
- bool类型赋值给其它类型:false->0,true->1;
- 浮点数赋值给整数类型:结果值仅保留浮点数中的整数部分;
- 整数值赋值给浮点类型:小数部分置0;
- 将一个超出表示范围的值赋值给无符号类型:结果时初始值对无符号类型表示数值总数取模后的余数。例如:8bit的unsigned char的表示范围:0~255,如果将此范围之外的值-1赋值给一个unsigned char类型,最终结果是255;
- 将带符号的值赋值给无符号类型:会导致未定义行为。
切勿混用带符号类型和无符号类型。
无符号数永远大于等于0,在循环中使用无符号数时,要谨慎。
表达式中混用带符号和无符号时,当带符号类型取值为负时会出现异常结果,因为带符号数回自动转换成无符号数。
int main()
{
unsigned int a = 10, b =42;
cout << a - b << endl; //结果为负时,对4294967296取模:4294967264
int c = -1;
unsigned int d = 1;
cout << c * d << endl; //结果为负时,对4294967296取模:4294967295
return 0;
}