Detailed explanation of type conversion during C++ division: division operation of negative integer and unsigned integer variable

Today, when I was writing a circular array question, because I didn't add an array length in front when writing the remainder operation, I wrote such a bug:

vector<int> nums = {
    
    -2,-1,1,-2,-2};
	
int i = 0;
i = (i + nums[i]) % nums.size();
cout << nums[i];

According to my previous understanding, i should be equal to -2 % 5 = -2, but miraculously, the code did not report an error due to nums[-2], but after verification, it was found that i was equal to 4. Why is this?

Taking this as an opportunity, I learned aboutType conversion in C++ divisionrelevant knowledge.
In C++11, relevant definitions are made for type conversion during operation, refer to Usual arithmetic conversions and integer conversion rank :

  1. Integer conversion rank: long long int > long int > int > short > signed char.
  2. The rank of any unsigned integer type is the same as that of its corresponding signed integer type.
  3. In a division operation, if one of the two operands is signed and the other is unsigned, if the conversion level of the type of the unsigned operand is greater than or equal to the conversion level of the signed operand, then the signed operand will be converted to unsigned The type of the symbolic operand.

In the standard library of C++11, the return type of the size() function is size_type, which is a supporting type of the vector class type and is defined to have the same meaning as the unsigned type (unsigned int, unsigned long). And it can be guaranteed to be large enough to store the length of any vector/string object.
According to the above conversion rules, the return value of the size() function is unsigned type (unsigned int, unsigned long), and its conversion level is greater than or equal to the int type of the divisor -2. Therefore, -2 will be converted to the type of the unsigned operand.

We write a division and remainder operation to verify:

vector<int> nums = {
    
    -2,-1,1,-2,-2};
	
cout << (-2) / nums.size() << endl;
cout << (-2) % nums.size();

The output result is:
insert image description here
using 5 * 858,993,458 + 4, the value 4,294,967,294 is obtained
and this number is exactly the complement of -2!
insert image description here
In summary, we have verified the correctness of the type conversion theory of the division operation between negative integers and unsigned integer variables in C++.

Guess you like

Origin blog.csdn.net/qq_43734019/article/details/119515505