-2
main()
{
    unsigned x=1;
    signed char y=-1;
    if(x>y)
        printf("x>y");
    else
        printf("x<=y");
}

output is: x<=y

But my question is in the statement unsigned x=1; there is no data type such as int or char. So what will the compiler assume? And in the statement signed char y=-1; Isn't it a error? and i also want to know how the program works.

  • 2
    1. `unsigned int`; 2. no, it isn't; 3. it works very well. –  Dec 11 '13 at 14:09
  • possible duplicate: [The “unsigned” keyword](http://stackoverflow.com/a/16568382/1825094) (What does `unsigned` without a specific type mean?) – Max Truxa Dec 11 '13 at 14:15
  • to assign characters to variable we follow i.e char y='z'. so how -1 can be stored in y? – user3087840 Dec 11 '13 at 14:36

3 Answers3

3

The default type for a "naked" unsigned is unsigned int.

The comparison works thanks to C's arithmetic promotions, which will convert both arguments to > to a suitable type before doing the comparison.

unwind
  • 391,730
  • 64
  • 469
  • 606
2
signed char y=-1;

-1 is generally stored in 2's complement form, but y is interpreted as positive. So y becomes a very large value, which is always greater than x.


Even if it's stored is sign+magnitude form, It is still a very large value, if treated as positive. And 1's complement complement of -1 is also greater than 1, if interpreted as positive value.

deeiip
  • 3,319
  • 2
  • 22
  • 33
  • How do you know it **will** be stored in 2's complement? It could be stored as 1's complement and in sign+magnitude representation as well. –  Dec 11 '13 at 14:11
  • Those are spelled "interpreted" and "positive". With "e" and **one** "s". –  Dec 11 '13 at 14:16
  • what is sign+magnitude? – user3087840 Dec 11 '13 at 14:30
  • In signed magnitude form a negative number is stored with most significant bit 1. And that bit is reserved for sign (i.e. negative-1, positive-0) – deeiip Dec 11 '13 at 14:32
0

This is related to the storage mechanism of the system.

Please check the following code where the o/p is shown in hex [direct storage format], for sake of simplicity.

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

int main()
{
        unsigned int ua = 1;
        signed int sa = -1;
        if (ua>sa)
                printf("ua>sa\n");
        else
                printf("sa>ua\n");

        printf("unsigned = 0x%x\t signed = 0x%x\n", ua, sa);

        return 0;
}

output:

[sourav@localhost Practice]# ./a.out 
sa>ua
unsigned = 0x1   signed = 0xffffffff
[sourav@localhost Practice]#

Hope this helps.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261