Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting from size_t to char and around

Tags:

c++

casting

c++11

I'm making the transition from C to C++11 now and I try to learn more about casting. At the end of this question you see a small program which asked a number as input and then shows it as number and as character. Then it is cast to a char, and after that I cast it back to a size_t.

When I give 200 as input, the first cout prints 200, but the second cout prints 18446744073709551560. How do I made it to print 200 again? Do I use the wrong cast? I have already tried different cast as dynamic and reintepret.

#include<iostream>

using namespace std;

int main(){  
  size_t value;

  cout << "Give a number between 32 and 255: ";
  cin >> value;

  cout << "unsigned value: " << value << ", as character: `" << static_cast<char>(value) << "\'\n";

  char ch = static_cast<char>(value);
  cout << "unsigned value: " << static_cast<size_t>(ch) << ", as character: `"  << ch << "\'\n";
}
like image 743
Michiel uit het Broek Avatar asked Dec 25 '22 04:12

Michiel uit het Broek


1 Answers

size_t is unsigned, plain char's signed-ness is implementation-defined.

Casting 200 to a signed char will yield a negative result as 200 is larger than CHAR_MAX which is 127 for the most common situation, an 8-bit char. (Advanced note - this conversion is also implementation-defined but for all practical purposes you can assume a negative result; in fact usually -56).

Casting that negative value back to an unsigned (but wider) integer type will yield a rather large value, because unsigned arithmetic wraps around.

You might cast the value to an unsigned char first (yielding the expected small positive value), then cast that the wider unsigned type.

Most compilers have a switch that lets you toggle plain char over to unsigned so you could experiment with that. When you come to write portable code, try to write code that will work correctly in both cases!

like image 200
DevSolar Avatar answered Jan 03 '23 05:01

DevSolar