Reputation: 35405
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?
Upvotes: 2
Views: 1550
Reputation: 56956
Comparing signed and unsigned types result in undefined behavior. Your program can and will print different results on different platforms.
Please see comments.
Upvotes: 1
Reputation: 1261
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.
Upvotes: 0
Reputation: 315
The signed value will get promoted to unsigned and therefore it will be bigger than 1.
Upvotes: 0
Reputation: 361
unsigned/signed is just short specification for unsigned int/signed int (source), so no, you don't have variable with "no data type"
Upvotes: 0
Reputation: 21628
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).
Upvotes: 6
Reputation: 91015
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
.
Upvotes: 2
Reputation: 62185
As far as I know, the signed value gets promoted to an unsigned value and so becomes very large.
Upvotes: 1
Reputation: 2238
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.
Upvotes: 2