Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unsigned integers in C [closed]

While i am running the program below it outputs like 109876543210-1-2-3-4-5-6-78-9-10-11-12-and s0 on. Why so? What is the concept of unsigned integer?

 main ()
   {
      unsigned int i;
       for (i = 10; i >= 0; i--)
                 printf ("%d", i);
   }
like image 853
amitshree Avatar asked Mar 11 '13 13:03

amitshree


People also ask

What is an unsigned integer in C?

C and C++ are unusual amongst languages nowadays in making a distinction between signed and unsigned integers. An int is signed by default, meaning it can represent both positive and negative values. An unsigned is an integer that can never be negative.

How are unsigned integers stored in C?

In the case of an unsigned integer, only positive numbers can be stored. In this data type, all of the bits in the integer are used to store a positive value, rather than having some reserved for sign information.

Does C have unsigned int?

In C, unsigned is also one data type in which is a variable type of int this data type can hold zero and positive numbers. There is also a signed int data type in which it is a variable type of int data type that can hold negative, zero, and positive numbers.

What does unsigned int mean?

An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295]. The signed integer is represented in twos complement notation. The most significant byte is 0 and the least significant is 3.


1 Answers

Unsigned integers are always non-negative, that is greater than or equal to 0. When you subtract 1 from 0 in an unsigned integer type you end up with MAX_INT.

Therefore, your for loop will never terminate.

However, you need to use "%u" not "%d" in your printf if you want it to print the unsigned value rather than the signed value.

like image 136
Vicky Avatar answered Oct 04 '22 11:10

Vicky