smm
smm

Reputation: 65

Difference Between reinterpret_cast Usage

Are these two cast statements the same? They produce the same results.

const std::int16_t i =  3;
char a[ 2 ];

*reinterpret_cast<std::int16_t*>(a) = i;
reinterpret_cast<std::int16_t&>(a)  = i;

Upvotes: 1

Views: 106

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254431

Yes, because of the implicit array-to-pointer conversion.

The first attempts to cast a pointer; so the array is converted to a pointer (to its first element) to allow that cast. Then you dereference the pointer, to write over the array's bytes.

The second casts a reference to the array into a reference to an integer; assignment to that reference again writes over the array's bytes.

If you were to try this with a non-array type, the first wouldn't compile; you'd have to explicitly take the address, &a, before casting that pointer.

Upvotes: 1

Related Questions