简体   繁体   English

为什么`(i <(str.size()-(3-vec.size()))`是真的?

[英]why `( i < (str.size()-(3-vec.size())) )` is true?

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    string str("0");
    vector<int> vec;
    int upper_bound = str.size()-(3-vec.size());
    int i = 0;

    if ( i < upper_bound ) // Line 1
        cout << "i < upper_bound - 1\n";
    else
        cout << "pass\n";

    if ( i < (str.size()-(3-vec.size())) ) // Line 2
        cout << "i < upper_bound - 2\n";
    else
        cout << "pass\n";        

    return 0;
}

Output is as follows: 输出如下:

pass
i < upper_bound

Question> Why Line 1 and Line 2 print different results? 问题>为什么第1行和第2行打印不同的结果?

Mathematically, str.size()-(3-vec.size()) is 1-(3-0) , which is -2. 在数学上, str.size()-(3-vec.size())1-(3-0) ,即-2。 However, since these are unsigned values, the result is also unsigned, and so has a large positive value. 但是,由于这些是无符号值,因此结果也是无符号的,因此具有较大的正值。

Converting this to int to initialise upper_bound technically gives undefined behaviour, but in practise will give you -2; 从技术上将其转换为int以初始化upper_bound会产生不确定的行为,但实际上会给您-2; so the first test passes. 所以第一次测试通过了。

The second test compares with the large unsigned value rather than -2. 第二个测试与较大的无符号值而不是-2比较。

The problem is that expression str.size()-(3-vec.size())) has some unsigned type. 问题在于表达式str.size()-(3-vec.size()))具有某些无符号类型。 So it may not be negative. 因此,它可能不是负面的。 It is an unsigned type due to 1) str.size() and vec.size() are of some unsigned types according to definitions of std::string::size_type and std::vector<int>::size_type 2) the usual arithmetic conversion. 由于1)str.size()和vec.size()是根据std::string::size_typestd::vector<int>::size_type定义的一些无符号类型,因此它是无符号类型2)通常的算术转换。

In the first expression you explicitly assigned an unsigned expression to type int. 在第一个表达式中,您明确分配了一个无符号表达式来键入int。 So as the sign bit is set then the value of this object is negative. 因此,当符号位被置位时,该对象的值为负。

To understand this try for example to execute these statements 要了解这一点,请尝试执行以下语句

std::cout << -1 << std::endl;
std::cout << -1u << std::endl;

or 要么

std::cout << 0u -1 << std::endl;

Here -1u and 0u - 1 have type unsigned int and the same bit combination as -1. 这里-1u和0u-1具有unsigned int类型,并且具有与-1相同的位组合。

While comparing signed and unsigned types, compiler will convert the signed types to unsigned. 在比较带符号和无符号类型时,编译器会将带符号的类型转换为无符号。 That creates the weird result. 那产生了奇怪的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM