C++ unsigned int 和 int 混用的问题

原文地址: https://blog.qjm253.cn/?p=358

问题引入

且看下面一段诡异的代码

#include <iostream>
using namespace std;

int main(){
  unsigned int a = 5;
  if(a < -6){           //下面的输出语句会执行
    cout << "unsigned 5 < -6" << endl;
  }
}
  • 执行上面的代码,会输出 “unsigned 5 < -6”
  • 这看起来一点都不科学 _(:з」∠)_

敲黑板,讲重点

!!!在c++里面,如果一个表达式里面同时有 unsigned int 和 int ,执行的时候会尝试把 int 转成 unsigned int。
- 这个时候如果int的值是非负的,执行的结果当然和预期一样
- 但是如果int的值是负数,它的值就变成 int的最大值 + 原值 => 其实是C++类型转换的锅,如果是int转unsigned,就会用int的最大值对原值取模

  • 验证一下 int 转 unsigned int 的时候编译器怎么处理的

    
    #include <iostream>
    
    using namespace std;
    
    int main(){
    unsigned int a = -1;
    unsigned int b = -2;
    
    cout << a << " " << b << endl;
    return 0;
    }
    • 执行上面的代码输出为

      4294967295 4294967294
    • 其中 232 - 1 = 4294967295

  • 举几个栗子加深理解

    
    #include <iostream>
    
    
    #include <string>
    
    
    using namespace std;
    
    int main(){
    
    //Example 1
    u_int a = -5;
    int b = 4;
    if(a + b > 0){
      cout << "(unsigned)-5 + 4 > 0 => and the value is: " << a + b << endl;
    }
    
    //Example 2;
    string s;
    if(s.size() < -1){
      cout << "s.size() < -1" << endl;
    }
    }
    • 以上代码的输出为

      (unsigned)-5 + 4 > 0 => and the value is: 4294967295
      s.size() < -1
    • 其中Example 1很好理解,执行 a + b 的时候,b被转成了unsigned int,变成了一个很大的正数

    • 而Example 2中,string对象的size()函数返回的也是一个无符号整数,所以也存在unsigned int 和 int 在同一个表达式里混用的问题。
    • 不解释 => u_int <=> unsigned int
发布了55 篇原创文章 · 获赞 29 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_33215972/article/details/80426358
今日推荐