-1

So today am learning about the signed and unsigned variables. So what i can make out is that signed can have positive, negative and zero values and unsigned can have only the positive values. So to try this through code i wrote this program in c:

#include <stdio.h>
#include <stdlib.h>


void main()
{
    int a=-10;
    unsigned int x=-4;
    printf("signed variable value is : %d\n Unsigned variable value is : %u",a,x);


}

SO as per my expectation output should be like this :

signed variable value is : -10
Unsigned variable value is : 4

But in reality it turned out to be like this:

signed variable value is : -10
Unsigned variable value is : 4294967292

Can any one explain this !!

R Sahu
  • 204,454
  • 14
  • 159
  • 270
Magnum
  • 83
  • 1
  • 5
  • it should be warning.. but some times 2^32 (range of an unsigned int ) - 4 = 4294967296 - 4 = 4294967292 – rabi shaw Apr 13 '15 at 05:26
  • @rabishaw there should not be a warning, this is how `unsigned int` is supposed to behave – M.M Apr 13 '15 at 05:27

3 Answers3

1

When you assign a negative value into a unsigned int and print it using the format specifier %u, 2's complement of that number will be taken into consideration.

So that x become 2's complement of -4, ie 4294967292

A similar question is asked here Assigning negative numbers to an unsigned int?

Community
  • 1
  • 1
niyasc
  • 4,440
  • 1
  • 23
  • 50
  • The link is different, it is asking about undefined behaviour caused by using the wrong format specifier – M.M Apr 13 '15 at 05:28
  • @MattMcNabb Just go through the answers. You can find what you need. – niyasc Apr 13 '15 at 05:29
0

The way that unsigned variables work is that they wrap around past 0 (both going forward and back), treating 0 as congruent to 232 (on a 32-bit system). To see this, try the following program:

#include <stdio.h>

int main()
{
    unsigned int test = 3;

    for (int i = 0; i < 10; ++i)
    {
         test = test - 1;
         printf("%u\n", test);
    }
}

Output (on a 32-bit system):

2
1
0
4294967295
4294967294
4294967293
4294967292
4294967291
4294967290
4294967289

Back to your code. -4 is of course the same as 0 - 4 so what you have gotten is the fourth item past 0 on this list.

NB. Your code does not have any errors apart from void main

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365
-2

The unsigned variable doesn't take the absolute value for you.

Since you are putting a negative value in it, it casts the signed integer value (-4) to a 4 byte unsigned variable.

I am guessing the negative values are stored as 2's complement here. Therefore what you get as a -4 on a unsigned 4byte variable is in fact 2^32 -4 (one wrap around) : 4294967292

Shervin
  • 409
  • 7
  • 13