0
void printchars()
{
  for (x=128;x<224;x++)
      write(x);

I want the x to be a char in the write function. How can i change the x to be treated by the write functions as a char, but an int in the loop?

Bartlomiej Lewandowski
  • 10,771
  • 14
  • 44
  • 75

2 Answers2

2

What is the point of making x an int if you're just going to strip away its range? That's what makes this a very strange request. You should just make x a unsigned char -- for(unsigned char x = 128; x <224; ++ x) { ....

If you just want to ensure you're calling the unsigned char template specialization of write<>, then call it like this:

write<unsigned char>(x);

If not, then you will have to use type casting:

write((unsigned char)x);

Edit: I just realized what you might be experiencing. My guess is that you originally used char but found something wrong with numbers over 127. You should probably be using unsigned char for x instead of either int or char. I edited my answer to accommodate this. char has a range of -128 to +127. unsigned char has a range of 0-255.

tenfour
  • 36,141
  • 15
  • 83
  • 142
  • 1
    C-style type casting is not recommended. static_cast can do the job here. – Oscar Korz Oct 07 '11 at 22:39
  • In cases like this it really doesn't matter. Purists prefer `static_cast` here but realists use whatever works when you're making a fundamentally unsafe cast. – tenfour Oct 07 '11 at 22:41
  • 1
    Better to learn the right thing than to learn when you can do the wrong thing "safely". – Oscar Korz Oct 07 '11 at 22:44
  • C++ has safer casts. No reason to use C's dangerous "make it work" cast. See: http://stackoverflow.com/questions/28002/regular-cast-vs-static-cast-vs-dynamic-cast – Oscar Korz Oct 07 '11 at 22:50
  • Although I just noticed the top answerer admits he uses C-style casts for numerical casts. Personally, I see no place in C++ for C casts. – Oscar Korz Oct 07 '11 at 22:51
  • Every construct in C++ is potentially unsafe. It's judging the situation at hand that removes the "potentially" from this decision. I am not saying one should never use C++ casts, I'm saying C-style casts are fine in this case. Go ahead and use `static_cast`, that's great, but don't pretend that `(char)` here is any less safe. – tenfour Oct 07 '11 at 22:56
1

Cast x to a char:

write(static_cast<char>(x));

Note that it is ok for x to be a char as the loop counter as well.

Oscar Korz
  • 2,457
  • 1
  • 18
  • 18