Casting from size_t to char and around

I am currently making a transition from C to C ++ 11 and I am trying to learn more about casting. At the end of this question, you see a little program that enters a query as a number and then displays it as a number and as a symbol. Then it is appended to the char, after which I return it to size_t.

When I give 200 as input, the first cout prints 200 and the second cout prints 18446744073709551560. How did I do this to print 200 again? Am I using the wrong translation? I have already tried different actors like 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";
}

      

+3


source to share


1 answer


size_t

is unsigned, simple char

signature is undefined.

Listing 200

for a signed char will fail as 200 is greater than CHAR_MAX

, which is the 127

most common situation, 8-bit char. (Extended note - this conversion is also implementation-defined, but for all practical purposes, you can accept a negative result, in fact usually -56

).

Casting that negative value back into an unsigned (but wider) integer type will give quite a lot of value, because unsigned arithmetic is wrapped around.



You can assign a value first unsigned char

(getting the expected small positive value) and then apply a wider unsigned type.

Most compilers have a switch that allows you to switch plain char

to unsigned

so you can experiment with that. When you come to write portable code, try writing code that works correctly in both cases!

+8


source







All Articles