Isn't it a generally a bad idea to convert from a larger integral type to a smaller signed if there is any possibility that overflow errors could occur? I was surprised by this code in C++ Primer (17.5.2) demonstrating low-level IO operations:
int ch;
while((ch = cin.get()) != EOF)
cout.put(ch); //overflow could occur here
Given that
- cin.get() converts the character it obtains to
unsigned char, and then toint. Sochwill be in the range0-255(exluding EOF). All is good. - But then in the
put(ch)expressionchgets converted back tochar. Ifcharissignedthen any value ofchfrom128-255is going to cause an overflow, surely?
Would such code be generally bad practice if I'm expecting something outside of ordinary input 0-127, since there are no guarantees how overflow is treated?
cin.getguarantees that if the return value isn'tEOFthen it's representable asunsigned char.cout.put(ch)statement.charvalues to be converted fromunsigned char, so this is fine. Note that the conversion is unspecified and not "overflow".