Search code examples
c++c++11castingunsigned-integer

Unsigned int not working C++


Following are different programs/scenarios using unsigned int with respective outputs. I don't know why some of them are not working as intended.

Expected output: 2

Program 1:

int main()
{
    int value = -2;
    std::cout << (unsigned int)value;

    return 0;
}

// OUTPUT: 4294967294

Program 2:

int main()
{
    int value;
    value = -2;
    std::cout << (unsigned int)value;

    return 0;
}

// OUTPUT: 4294967294

Program 3:

int main()
{
    int value;
    std::cin >> value; // 2
    std::cout << (unsigned int)value;

    return 0;
}

// OUTPUT: 2

Can someone explain why Program 1 and Program 2 don't work? Sorry, I'm new at coding.


Solution

  • You are expecting the cast from int to unsigned int to simply change the sign of a negative value while maintaining its magnitude. But that isn't how it works in C or C++. when it comes to overflow, unsigned integers follow modular arithmetic, meaning that assigning or initializing from negatives values such as -1 or -2 wraps around to the largest and second largest unsigned values, and so on. So, for example, these two are equivalent:

    unsigned int n = -1;
    unsigned int m = -2;
    

    and

    unsigned int n = std::numeric_limits<unsigned int>::max();
    unsigned int m = std::numeric_limits<unsigned int>::max() - 1;
    

    See this working example.

    Also note that there is no substantial difference between programs 1 and 2. It is all down to the sign of the value used to initialize or assign to the unsigned integer.