基本数据类型

基本数据类型的长度

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;
}

基本数据类型之间的转换

  1. 短类型赋值给长类型时,会发生自动转换,合法;
  2. 非bool类型的值赋值给bool类型:0->false; 非0->true;
  3. bool类型赋值给其它类型:false->0,true->1;
  4. 浮点数赋值给整数类型:结果值仅保留浮点数中的整数部分;
  5. 整数值赋值给浮点类型:小数部分置0;
  6. 将一个超出表示范围的值赋值给无符号类型:结果时初始值对无符号类型表示数值总数取模后的余数。例如:8bit的unsigned char的表示范围:0~255,如果将此范围之外的值-1赋值给一个unsigned char类型,最终结果是255;
  7. 将带符号的值赋值给无符号类型:会导致未定义行为。

切勿混用带符号类型和无符号类型。

无符号数永远大于等于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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值