C Programming language

adplus-dvertising
Data types in C: signed and unsigned
Previous Home Next

Integer signed and unsigned

we know in advance that the value stored in a given integer variable will always be positive—when it is being used to only count things, for example. In such a case we can declare the variable to be unsigned as:

unsigned int num_students ;

an unsigned integer still occupies two bytes. This is how an unsigned integer can be declared:

unsigned int i ;
unsigned i ;

Like an unsigned int, there also exists a short unsigned int and a long unsigned int. By default a short int is a signed short int and a long int is a signed long int.

Char signed and unsigned

Parallel to signed and unsigned ints (either short or long), similarly there also exist signed and unsigned chars, both occupying one byte each, but having different ranges. To begin with it might appear strange as to how a char can have a sign.

Consider the statement
char ch = 'A' ;
Here what gets stored in ch is the binary equivalent of the ASCII value of 'A' (i.e. binary of 65). And if 65's binary can be stored, then -54's binary can also be stored (in a signed char). A signed char is same as an ordinary char and has a range from -128 to +127.

if we are bent upon writing the program using unsigned char, it can be done as shown below. The program is definitely less elegant, but workable all the same.

main( )
{
unsigned char ch ;
for ( ch = 0 ; ch <= 254 ; ch++ )
printf ( "\n%d %c", ch, ch ) ;
printf ( "\n%d %c", ch, ch ) ;
}
Previous Home Next