Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why unsigned int contained negative number

Tags:

c

printf

unsigned

What I know about unsigned numerics (unsigned short, int and longs), that It contains positive numbers only, but the following simple program successfully assigned a negative number to an unsigned int:

  1 /*
  2  * =====================================================================================
  3  *
  4  *       Filename:  prog4.c
  5  *
  6  * =====================================================================================
  7  */
  8 
  9 #include <stdio.h>
 10 
 11 int main(void){
 12 
 13     int v1 =0, v2=0;
 14     unsigned int sum;
 15     
 16     v1 = 10;
 17     v2 = 20;
 18     
 19     sum = v1 - v2;
 20     
 21     printf("The subtraction of %i from %i is %i \n" , v1, v2, sum);
 22     
 23     return 0;
 24 }

The output is : The subtraction of 10 from 20 is -10

like image 222
Muhammad Hewedy Avatar asked May 11 '10 02:05

Muhammad Hewedy


People also ask

What if unsigned int is negative?

You simply cannot assign a negative value to an object of an unsigned type. Any such value will be converted to the unsigned type before it's assigned, and the result will always be >= 0.

Is unsigned integer always positive?

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

What happens when an unsigned int goes negative C++?

An unsigned integer will never be a negative value, the smallest value it can be is 0 (zero). The values you get are not garbage. Assigning -1 to an unsigned type will give you the maximum value that variable can hold.

Does int contain negative numbers?

Integers: Integers are the set of numbers including all the positive counting numbers, zero as well as all negative counting numbers which count from negative infinity to positive infinity. The set doesn't include fractions and decimals.


1 Answers

%i is the format specifier for a signed integer; you need to use %u to print an unsigned integer.

like image 174
James McNellis Avatar answered Nov 04 '22 09:11

James McNellis