Converting signed types

Signed to unsigned conversions can happen and can cause unexpected results. For example:

    int s = -3;     unsigned int u = s;

The unsigned short variable will be assigned with a value of 0xfffffffd, that is, the two's compliment of 3. This may be the result you want, but it is an odd way of getting it.

Interestingly, if you try and compare these two variables, the compiler will issue a warning:

    if (u < s) // C4018     cout << "u is smaller than s" << endl;

The Visual C++ warning C4018 given here is '<': signed/unsigned mismatch, which says that you cannot compare a signed and unsigned type, and to do so would need a cast.

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.