Thursday, July 9, 2009

In C language Why a character variable is ranging from -128 to +127.?

In C language Why a character variable is ranging from -128 to +127

In C language Why a character variable is ranging from -128 to +127.?
Not just the char type, but every type in the C language is defined by the range of values it can be assigned to. The C standards committee thought that, it would be wiser to specify a range and let the CPU manufacturers and compiler writers decide on how to implement them. So, a char normally takes the size of the CPU (32bits, 16bits, etc) although, strictly speaking, it should take 8 bits. It can be made to use 8bits by providing some hints to the compiler.





Another possible answer could be, the char type was meant to represent alphabets and numbers and other signs of the English language. English was the only language in which computer development happened in earlier days of computing. And, the 256 values that a char type could be assigned to was enough to accommodate all the alphabets, numbers, signs, operators and some special symbols like @ and $.





One more reason is, to a C compiler, int(or size of the CPU -- 16bits, 32bits, etc) is the default type. Every other type is converted into an (signed) int for easier handling without losing anything. This means, double or float is not converted into an int by the compiler. char being smaller than int by it definition of range, is treated as an int and hence the negative values apply to char.
Reply:The length/storage capicity depends on memory model of programing languages. When c-language was developed only ASCII cahracters are in consideration and hence the number of ASCII Cahracters are 256(128+128) therefore char holds all ASCII(alphabets,symbols, special keys, numbers etc) characters used in computer. Some later time concept of Unicode was introduced and Unicode holds alomost all characters of world languages and hence length of unicode is inscreased.





Some ASCII Code and Corresponding Characters are





A=65


B=66


C=67


and so on
Reply:Because you are treating it as a signed 1 byte (8 bits) datatype. Meaning it can hold 2**8 = 256 values.





|-128| + |0| + |127| = 256

plum

No comments:

Post a Comment