hi,
We use %d to print int values and %c to print char values..like this how can we print unsigned char values???
Thanx.
Printable View
hi,
We use %d to print int values and %c to print char values..like this how can we print unsigned char values???
Thanx.
%c is also used for unsigned char's.
If you want to print the numeric value (eg print 65 for 'A' in the typical ASCII character set) promote to int or unsigned and use %d or %u respectively.
ok..
If we declare a variable as char then its range would be -128 to 127..
but if we assign value >127 the variable accepts it and prints the corresponding character as per ASCII value..
So i'm confused that it won't defer whether the variable is declared as "char" or "unsigned char"
This statement may be true on your implementation. But there are several ways in which that statement is "implentation defined".
First, in C, there are three char types: char, signed char, unsigned char. Whether char is signed or unsigned is implementation defined. Your statement assumes an implementation where char is signed. This is different than the other integer types where, for example, signed int and int are the same type.
Second, in C, the number of bits in a char, signed char or unsigned char is implementation defined. The macro CHAR_BIT in <limits.h> gives the number of bits. It must be at least 8. Your statement assumes an implementation where CHAR_BIT is 8.
Third, in C99, signed values have one of three implementation defined representations: two's complement, one's complement, and sign-magnitude. Your statement that the range is -128 to 127 assumes a two's complement implementation for signed char values with CHAR_BIT 8. By the way, there are macros in <limits.h> that give the range of values for signed char, unsigned char, and char: SCHAR_MIN, SCHAR_MAX, UCHAR_MAX, CHAR_MIN, and CHAR_MAX. Using these macros, provides some degree of portability.
Forth, in C99, there is a "basic execution set" of characters that are required to be positive. It is implementation defined what are the values of other characters stored in char.
This discussion probably does not help you with your confusion. However, you may want to confirm if any of these implementation defined assumptions is not what your implementation has selected. The most likely one to be different is that the implementation you are using has selected char is to be unsigned.
You may want to find one of the draft standards or buy a copy of the standard to help you understand your issue. I am always impressed that the volunteers on the standards committee have done such a good job dealing with all the various implementations that pre-dated the ANSI 1989 standard.
What happens for signed value overflow is "undefined behavior". However, I have found that for two's complement implementations, there is fairly predicable behavior. The language standard does not guaranty this behavior.