Hello everyone,
I just started learning C and don't quite understand whether you can simply store a non ASCII character (single byte character with a decimal value above 127) in a variable defined as a char. On my OS, the default char is signed. However, getchar() or similar functions seem to return a positive integer, possibly exceeding 127 (except the negative EOF value).
Section 6.3.1.3 of the standard (latest version ISO/IEC 9899:1999) seems to say that the handling of this overflow:
Code:
char c = 170; /* char is by default signed on this OS causing an overflow */
is implementation-defined or an implementation-defined signal is raised.
In practice, the overflow seems to not cause too much trouble on my computer, as the original value (0-255) can be obtained by using a cast, like I did in the code below. However, I have no idea if other (possibly smarter) processors might convert +170 to +127 inseatd of some negative value though. So, I would like to know whether this overflow should just be ignored, and is handled reasonably protably; or if getchar() and similar functions can only be used with ASCII files; or if the char has to be explicitly defined as an unsigned char? The latter causes other problems though, because most standard functions expect a char, not an unsigned char, right? Furthermore, is there ever a possibility that an integer or float/double overflow overwrites adjacent memory, instead of just rolling over or staying at MIN or MAX?
Thanks for reading! Below is just some short sample code.
Code:
#include <stdio.h>
int main(void) {
char c;
int i;
printf( "Enter one character: " );
i = getchar();
c = i;
printf( "signed c equals: %d\t unsigned c equals: %d\n", c, (unsigned char)c );
c = 170; /* generates compiler overflow warning */
printf( "signed c equals: %d\t unsigned c equals: %d\n", c, (unsigned char)c );
/* prints signed c equals: -86 unsigned c equals: 170 */
return 0;
}