magician
magician

Reputation: 1

Confusion about Casting among Signed and Unsigned

Recently I am learning about casting among data type. So I try this:

    unsigned int a = 4294967295;
    int b = -1;
    if (a == b) {
        cout << "a == b" << endl;
    } else {
        cout << "a != b" << endl;
    }

    unsigned short c = 65535;
    short d = -1;
    if (c == d) {
        cout << "c == d" << endl;
    } else {
        cout << "c != d" << endl;
    }

The output is:

a == b
c != d

I have learned that -1 and 65535U are equal when encoded using 16bits. So why variable c and d are not equal when compared?

I try to use explicit conversion:

    unsigned short e = static_cast<unsigned short>(d);
    if (c == e) {
        cout << "c == e" << endl;
    } else {
        cout << "c != e" << endl;
    }

The output is

c == e

so what is the differnece?

My system is win11 x64.

Thanks in advance.

Upvotes: 0

Views: 63

Answers (0)

Related Questions