Datatypes and datatype modifiers in C-Collection of common programming errors

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

#include 

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

        if(AbcXyz)
                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?

  1. 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.

  2. 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).

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

  4. 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.

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

    Please see comments.

  6. unsigned/signed is just short specification for unsigned int/signed int (source), so no, you don’t have variable with “no data type”

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

  8. 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.

Originally posted 2013-11-09 20:46:00.