-1

I am wondering why this code will output -5 , since they are of different types, and -5 is a very large in unsigned considering 2's complement

#include <stdio.h>
    int main()
    {
        unsigned int x = -5; //
        printf("%d", x);

    }

I am very confused, how a signed int be converted into unsigned? thanks!

Yyh
  • 59
  • 1
  • 8
  • This code actually does the exact opposite: int interpretes an `unsigned` as `int`. There is no conversation, but undefined behaviour. – too honest for this site Jan 07 '17 at 12:14
  • @Ashi: The code does the opposite of what the text asks for. – too honest for this site Jan 07 '17 at 12:14
  • bytes... 32 bits... store the same information. There is just an algorithm that take those 4 bytes and says... well how do I have treat them? unsigned? than this is a huge number, signed, than this is a negative number, float than this is... don't know what, but another number – jurhas Jan 07 '17 at 14:10

1 Answers1

0

The initial conversion occurs when -5 is assigned to an unsigned int. At that point you have, as suggested, a very large number (the actual value depending on the number of bits in int on your machine).

The second "conversion" is really an interpretation. printf is asked to take a set of bits and print them out as though they represent an unsigned integer value. This is why the output is -5

levengli
  • 1,091
  • 7
  • 18