In compiling some interview test questions, I'm currently taking examples from various sources and running through them to gauge their difficulty level and correctness. I've come across one that I think is broken, but it's also possible I'm missing something: if I am, I want to know, not only for my own knowledge but then it would also indicate that this is potentially a good, tricky question. I'd like you to help me regain my sanity and re-affirm the trust I have placed in myself. :D
What is the correct way to cast p at the placeholder "???" in the following code?
#include <iostream> using namespace std; uint16_t hash(void *p) { uint32_t val = ???; return (uint16_t)(val ^ (val >> 16)); } int main(int argc, char *argv[]) { uint32_t a[20]; for(uint32_t i = 0; i < 20; ++i) { a[i] = i; cout << hash(a + i) << endl; } }
Choose one:
static_cast<uint32_t>(p)
dynamic_cast<uint32_t>(p)
reinterpret_cast<uint32_t>(p)
const_cast<uint32_t>(p)
Ignoring for a moment that the call to hash
must be ::hash
to guarantee disambiguity with the standard library (e.g. this line doesn't compile for me in GCC 5.3.0, C++14 mode), I have a problem with the question.
Firstly, it's not clear what the program's supposed to do. Hash the array values, or hash the element locations? Because at the moment the function is receiving pointers-to-elements, but all the available answers assume that those pointers are to be themselves converted to uint32_t
and used as the hash value. If that's the case, then even if you use a reinterpret_cast
then there is a bug because sizeof(void*)
may not be sizeof(uint32_t)
; val
in that function should be intptr_t
instead. The use of uint32_t
for the type of the array elements themselves just confuses matters further if that's effectively a co-incidence.
Or the function is supposed to hash the value and the correct answer is not in the list: *static_cast<uint32_t*>(p)
.
The "correct" answer is apparently reinterpret_cast<uint32_t>(p)
, which makes me think the intention of the program is to hash the array element addresses.
Am I imagining these problems?
Is the question clear and is the solution one of the four choices offered?