# Analysis and solution of C + + implicit conversion

Time：2021-10-25

Let’s first look at the example code:

``````
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main()
{
unsigned int a;
int b = -1;
while (cin >> a)
{
if (a > b)
{
cout << "a > b" << endl;
}
else if (a < b)
{
cout << "a < b" << endl;
}
else
{
cout << "a == b" << endl;
}

}
return 0;
}``````

Explanation:

If there are multiple types of operands for arithmetic operation or relational operation, they need to be converted to the same type.

This involves unsigned operands

If the operands of an operator are inconsistent, they will be converted to the same type. However, if the type of an operand is unsigned, the result of the conversion depends on the relative size of each integer type in each integer type in the machine.

As usual, integer promotion is performed first. If the type of the result matches, no further conversion is required. If the types of two (promoted) operands are either signed or unsigned, the operands of the small type are converted to the larger type.

If one operand is unsigned and the other operand is signed, and the unsigned type is not less than the signed type, the signed operand is converted to unsigned. For example, unsigned int and int in the above program, the operand of type int is converted to type unsigned int. If the value of type int is exactly negative, it is converted to the remainder of the total number of unsigned ints after modulo removal. This leads to the strange situation of a < B.

For example, an unsigned char with an 8-bit size can represent a value in the range of 0 to 255. If we assign a value outside the range, the actual result is the remainder obtained after the value modulus 256. Therefore, the result of assigning – 1 to an unsigned char with an 8-bit size is 255.

The other case is that the signed type is larger than the unsigned type. At this time, the conversion result depends on the machine. If all values of the unsigned type can exist in the signed type, the operand of the unsigned type is converted to the signed type. If not, the operand with signed type is converted to unsigned type.

This is the end of this article on the analysis and solutions of C + + implicit conversion problems. For more information about implicit conversion problems found in C + +, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!

## OC basis

IOS development interview essential skills chart.png What are objects and what are the objects in OC? An object is an instance of a class; Is an instance created through a class, which is generally called an instance object; Common objects in OC include instance objects, class objects, and metaclass objects; What is a class? What […]