Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

Why is 'char' signed by default in C++?

Why is char by default in the range from -128 to 127 when it is supposed to represent a 'character' whose textual reprezentations are in the range from 0 to 255? In this sense I'd guess char should be unsigned by default, only if we intended to treat it only like 'numbers' we'd have to add 'signed' keyword. Therefore should I rather use unsigned char when I work with text files?

Also I don't understand why std::ofstream's read and write functions use char and not unsigned char when I need to work with binary files. There I don't care about signed-ness, do I? Moreover I've made successfuly a copy of a JPEG file using signed char like this:

//..open all streams..
char c;
while(input.peek()!=EOF){
    input.read(&c,1);   //std::ifstream input;
    output.write(&c,1); //std::ofstream output;
} 
//..close all streams..

Since it works I think the read reads an unsigned bytes (in image processing an unsigned char is commonly used) and sets c so that the value has some accidental signed interpretation in 2's complement. I need to create a histogram of values, but I get a runtime error because I use signed char as index. Isn't it rather stupid that I have to use some cast uc = (unsigned char)c;? when there could be at least a simple overload of read/write for unsigned char?

question from:https://stackoverflow.com/questions/17097537/why-is-char-signed-by-default-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It isn't.

The signedness of a char that isn't either a signed char or unsigned char is implementation-defined. Many systems make it signed to match other types that are signed by default (like int), but it may be unsigned on some systems. (Say, if you pass -funsigned-char to GCC.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...