Search code examples
cintunsigned-integer

How does C store negative numbers in signed vs unsigned integers?


Here is the example:

#include <stdio.h>

int main()
{
    int x=35;
    int y=-35;
    unsigned int z=35;
    unsigned int p=-35;
    signed int q=-35;
    printf("Int(35d)=%d\n\
Int(-35d)=%d\n\
UInt(35u)=%u\n\
UInt(-35u)=%u\n\
UInt(-35d)=%d\n\
SInt(-35u)=%u\n",x,y,z,p,p,q);

    return 0;
}

Output:

Int(35d)=35
Int(-35d)=-35
UInt(35u)=35
UInt(-35u)=4294967261
UInt(-35d)=-35
SInt(-35u)=4294967261

Does it really matter if I declare the value as signed or unsigned int? Because, C actually only cares about how I read the value from memory. Please help me understand this and I hope you prove me wrong.


Solution

  • Does it really matter if I declare the value as signed or unsigned int?

    Yes.

    For example, have a look at

    #include <stdio.h>
    
    int main()
    {
        int a = -4;
        int b = -3;
        unsigned int c = -4;
        unsigned int d = -3;
        printf("%f\n%f\n%f\n%f\n", 1.0 * a/b, 1.0 * c/d, 1.0*a/d, 1.*c/b);
    }
    

    and its output

    1.333333
    1.000000
    -0.000000
    -1431655764.000000
    

    which clearly shows that it makes a huge difference if I have the same byte representation interpreted as signed or unsigned.