A Complete Advanced Description About int Datatype
Int's are those datatypes which are used represent the real numbers either positive or negative with a specific range.mainly int divides into 2 types signed or unsigned int.
signed int are same as plain int. they can defined through 3 ways 1.int_
signed int can be positive,negative or 0.It has minimum range of atleast -32767 to 32767.
while unsigned int are the int who always have positive value and their range is 0 to 65535.
Representation of integers in memory
since int are always performed modulo 2^n where n is no. of bits in that particular int.the total range of numbers that can represent a number.2^16 is the same as 65536,which since count from 0,is the same as 0-65535.this obviously matches up with the values for an unsigned int,So you can see that this is how that type operates.
How computer Differentiate Between Signed & Unsigned int
Basically, A process called two's complement is used to transform positive numbers into negative numbers.the side effect of this is that the most significant bit is used to tell the computer if the number is positive or negative. If the most significant bit is 1,then number is negative.if it is 0,the no. is positive.
Since the first bit is not used in the actual calculation of the value of number,you only have 15 bits that can be used to give the value of the number.2^15 is 32768,which means that we can represent from 0 to 32767 & using signed bit,from 0 all the way down to -32768.
so yes,int can be negative number, because it reads the signed bit,and unsigned int can be a negative number ,but can achieve larger positive values than int can.that is also why you have to specify if an integer is signed or unsigned to printf ,so it knows whether to read the sign bit or not.
Special Problem with the Important Note
Note-In c++ or c if the types of two operands differ from one another,then operand with the "lower type" will be promoted to type of "higher type " operand.
Int's order from high to low type..
#unsigned long int
#signed int or int
TRICKY PROBLEM--what is the output of 25u-30?
here we use the concept which we discuss it just before this..here int is lower type and unsigned int is higher type so the int will convert into unsigned int means 50 becomes 50u so,we get 25u-30u through this we can easily get -5u.as we know that unsigned int are always positive but here we have negative unsigned int means the arithmetic operation overflows (the result does not fit in result type),the behaviour is undefined,it may wrap around according to rules of representation and the unsigned integer arithmetic is always performed modulo 2^n where n is the no. of bits in that partiocular int.eg-for unsigned int,adding 1 to UINT_MAX gives 0, and subtracting 1 from 0 give UINT_max.
so here we can easily write -5u like this (0u-1u)-4u..as we discuss just above that subtracting 1 from 0 give UINT_MAX means it give 65535 and 4u means 4 so 65535-4 we get 65531.