|
The impression is that the two sides of == are unified as an unsigned number for comparison, but today I encountered a problem. I wrote the code and tested it, and I don't understand it :(
The following code part1 is a comparison of signed and unsigned numbers of different lengths. It seems that the contents of their respective memories are directly compared after expanding to the same length, but from the part2, the result is not the case.
How do you understand it? Thank you very much! !! !! !! !!
#include <iostream>
using namespace std;
int main ()
{
/ * part 1 * /
cout << "(bool) ((unsigned long) -5 (" << hex << (unsigned long) -5 << ")"
<< "== (unsigned short) -5) (" << hex << (unsigned short) -5 << "):"
<< (((unsigned long) -5 == (unsigned short) -5)? "true": "false") << endl;
cout << "(bool) ((signed long) -5 (" << hex << (signed long) -5 << ")"
<< "== (signed short) -5) (" << hex << (signed short) -5 << "):"
<< (((signed long) -5 == (signed short) -5)? "true": "false") << endl;
cout << "(bool) ((unsigned long) -5 (" << hex << (signed long) -5 << ")"
<< "== (unsigned short) -5) (" << hex << (signed short) -5 << "):"
<< (((unsigned long) -5 == (signed short) -5)? "true": "false") << endl;
cout << "(bool) ((signed long) -5 (" << hex << (unsigned long) -5 << ")"
<< "== (signed short) -5) (" << hex << (unsigned short) -5 << "):"
<< (((signed long) -5 == (unsigned short) -5)? "true": "false") << endl;
/ ************************************************* ************ /
/ * part 2 * /
signed short x = -1;
unsigned short y = 65535;
cout << "(bool) (x (" << hex << x << ") == y (" << hex << y << ") ="
<< (x == y? "true": "false") << endl;
x = 0xffff;
y = 0xffff;
cout << "(bool) (x (" << hex << x << ") == y (" << hex << y << ") ="
<< (x == y? "true": "false") << endl;
cin.get ();
} |
|