Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The real difference between "int" and "unsigned int"

Tags:

c

int:

The 32-bit int data type can hold integer values in the range of −2,147,483,648 to 2,147,483,647. You may also refer to this data type as signed int or signed.

unsigned int :

The 32-bit unsigned int data type can hold integer values in the range of 0 to 4,294,967,295. You may also refer to this data type simply as unsigned.

Ok, but, in practice:

int x = 0xFFFFFFFF; unsigned int y = 0xFFFFFFFF; printf("%d, %d, %u, %u", x, y, x, y); // -1, -1, 4294967295, 4294967295 

no difference, O.o. I'm a bit confused.

like image 381
Fabricio Avatar asked Jan 28 '12 13:01

Fabricio


People also ask

What is difference between int and unsigned int?

A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295].

What is the difference between unsigned and unsigned int?

There is no difference. unsigned and unsigned int are both synonyms for the same type (the unsigned version of the int type).

What is difference between signed and unsigned?

The term "unsigned" in computer programming indicates a variable that can hold only positive numbers. The term "signed" in computer code indicates that a variable can hold negative and positive values.

What is unsigned integer?

Unsigned Integers (often called "uints") are just like integers (whole numbers) but have the property that they don't have a + or - sign associated with them. Thus they are always non-negative (zero or positive). We use uint's when we know the value we are counting will always be non-negative.


2 Answers

Hehe. You have an implicit cast here, because you're telling printf what type to expect.

Try this on for size instead:

unsigned int x = 0xFFFFFFFF; int y = 0xFFFFFFFF;  if (x < 0)     printf("one\n"); else     printf("two\n"); if (y < 0)     printf("three\n"); else     printf("four\n"); 
like image 121
cha0site Avatar answered Oct 17 '22 04:10

cha0site


Yes, because in your case they use the same representation.

The bit pattern 0xFFFFFFFF happens to look like -1 when interpreted as a 32b signed integer and as 4294967295 when interpreted as a 32b unsigned integer.

It's the same as char c = 65. If you interpret it as a signed integer, it's 65. If you interpret it as a character it's a.


As R and pmg point out, technically it's undefined behavior to pass arguments that don't match the format specifiers. So the program could do anything (from printing random values to crashing, to printing the "right" thing, etc).

The standard points it out in 7.19.6.1-9

If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

like image 36
cnicutar Avatar answered Oct 17 '22 04:10

cnicutar