Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C style cast work but reinterpret_cast doesn't?

So I have a two char array

unsigned char v[2];

I want to show the value of v[0] as a number from 0 to 255 but

cout << v[0] << endl; //prints some garbage

cout << (void*)v[0] << endl; //prints the right thing but in hex

So I tried

cout << (int)v[0] << endl;

or

printf("%d\n", v[0]);

This shows exactly what I wanted but I don't like it at all. Also what I don't understand at all is why this doesn't work:

cout << reinterpret_cast<int>(v[0]) << endl; //compiler error
like image 244
Gabi Avatar asked Aug 18 '12 18:08

Gabi


1 Answers

(In layman's terms) reinterpret_cast is used to interpret the bits of an object as another type in an implementation-defined manner. You don't want that: you want a conversion (from char to int). Use static_cast instead.

(All possible uses of reinterpret_cast are listed in 5.2.10; this is not one of them.)

like image 59
eq- Avatar answered Oct 11 '22 14:10

eq-