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?
-
The default type in C is
int
. Thereforeunsigned
is a synonym forunsigned 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.
-
Two things are happening.
-
The default data type in C in int. Thus you have variables of type signed int and unsigned int.
-
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).
-
-
As far as I know, the signed value gets promoted to an unsigned value and so becomes very large.
-
int
is the “default” type in C.unsigned Abc
meansunsigned int Abc
just likelong L
meanslong 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 possibleunsigned int
. -
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.
Originally posted 2013-11-09 20:46:00.