1

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 to int. So ch will be in the range 0-255 (exluding EOF). All is good.
  • But then in the put(ch) expression ch gets converted back to char. If char is signed then any value of ch from 128-255 is 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?

3
  • 3
    cin.get guarantees that if the return value isn't EOF then it's representable as unsigned char. Commented Dec 17, 2015 at 15:08
  • @KerrekSB I thought that was what I said. Maybe I should've been clearer, my concern is with the cout.put(ch) statement. Commented Dec 17, 2015 at 15:16
  • Ah, yes. As a rule, all the IO functions consider char values to be converted from unsigned char, so this is fine. Note that the conversion is unspecified and not "overflow". Commented Dec 17, 2015 at 15:48

2 Answers 2

1

There are rules for integer demotion.

When a long integer is cast to a short, or a short is cast to a char, the least-significant bytes are retained.

As seen in: https://msdn.microsoft.com/en-us/library/0eex498h.aspx

So the least significant byte of ch will be retained. All good.

Sign up to request clarification or add additional context in comments.

Comments

0

Use itoa, if you want to convert the integer into a null-terminated string which would represent it.

char *  itoa ( int value, char * str, int base );

or you can convert it to a string , then char :

std::string tostr (int x){
    std::stringstream str;
    str << x;
    return str.str();}

convert string to char

string fname;
char *lname;
lname = new char[fname.lenght() + 1];
strcpy(f, lname.c_str());

if you see "Secure Error" disable it with #Pragma

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.