codeJack
codeJack

Reputation: 2503

c-casting to type against c-casting to type's reference

In c++, what is the difference in c-casting to the type or to the reference of the type ?

foo = (unsigned int) whatever;  

// Is this the same as: 
foo = (unsigned int&) whatever;  

Upvotes: 1

Views: 156

Answers (1)

AnT stands with Russia
AnT stands with Russia

Reputation: 320421

No, it is not even remotely the same.

(In some cases the exact nature of the cast depends of what whatever is. I will assume that the type of whatever is unrelated to unsigned int.)

C-casting to reference type unsigned int & is equivalent to performing a reinterpret_cast to that type

foo = reinterpret_cast<unsigned int &>(whatever);  

which is by definition equivalent to

foo = *reinterpret_cast<unsigned int *>(&whatever);  

whatever is required to be a lvalue in this case.

In other words, casting to reference is just another method of type punning. You are simple reinterpreting the memory occupied by whatever as an unsigned int object. In general case the behavior is undefined. For example, if sizeof whatever is smaller than size of unsigned int, the reinterpretation will also involve some "wild" memory that does not even belong to whatever.

Meanwhile a non-reference C-cast is just a value conversion, not memory reinterpretation. For arithmetic conversions to unsigned int it is equivalent to static_cast (but if whatever is a pointer, it is equivalent to reinterpret_cast). It reads the value of whatever and converts it to unsigned int type according to the language conversion rules (if the conversion exists).

For example, this

float f = 5;
unsigned int i = (unsigned int) f;

will convert the value of f to type unsigned int, which means that i will receive value 5. At the same time, if on your platform sizes unsigned int and float have the same size, then this

unsigned int i = (unsigned int &) f;

will actually reinterpret internal object representation of float object f with value 5 as an object of type unsigned int. The resultant value of i is generally unpredictable. Typically it won't be even close to 5 (in popular implementations you will simply receive the IEE754 representation of the original float value in i).

Upvotes: 6

Related Questions