开发者

Datatypes and datatype modifiers in C

I am pretty new to C. I recently came across this piece of code in C:

#include <stdio.h>

int main()
{
        unsigned Abc = 1;
        signed Xyz = -1;

     开发者_如何转开发   if(Abc<Xyz)
                printf("Less");
        else
        if(Abc>Xyz)
                printf("Great");
        else
        if(Abc==Xyz)
        printf("Equal");
        return 0;
}

I tried running it and it outputs "Less". How does it work? What is the meaning of unsigned Abc? I could understand unsigned char Abc, but simply unsigned Abc? I am pretty sure Abc is no data type! How(and Why?) does this work?


Two things are happening.

  1. The default data type in C in int. Thus you have variables of type signed int and unsigned int.

  2. When and unsigned int and a signed int are used in an expression the signed int is converted to unsigned before the expression is evaluated. This will cause signed(-1) to turn into a very large unsigned number (due to 2's complement representation).


The default type in C is int. Therefore unsigned is a synonym for unsigned int.

Singed integers are usually handled using twos complement. This means that the actual value for 1 is 0x0001 and the actual value for -1 is 0xFFFF.


int is the "default" type in C. unsigned Abc means unsigned int Abc just like long L means long int L.

When you have an expression that mixes signed and unsigned ints, the signed ints get automatically converted to unsigned. Most systems use two's complement to store integers, so (unsigned int)(-1) is equal to the largest possible unsigned int.


As far as I know, the signed value gets promoted to an unsigned value and so becomes very large.


Comparing signed and unsigned types result in undefined behavior. Your program can and will print different results on different platforms.

Please see comments.


unsigned/signed is just short specification for unsigned int/signed int (source), so no, you don't have variable with "no data type"


The signed value will get promoted to unsigned and therefore it will be bigger than 1.


Add the following line after signed Xyz = -1;

printf("is Abc => %x less than Xyz => %x\n",Abc,Xyz);

and see the result for yourself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜