reinterpret_cast strangeness ( comma separated expression )

c++

Solution

`reinterpret_cast` accepts an expression. What you have in the parenthesis is an expression - the "," operator with two sub-expressions, which will evaluate to the result of last sub-expression.

Problem

While debugging some of our code (C++) I found this: ``` inline std::string BufferToStr( const unsigned char* buffer, int index, size_t length) { std::string retValue(reinterpret_cast<const char*>(&buffer[index], length)); return retValue; } ``` The issue with this code (overlooking the lack of pointer and string length checks) is that the closing parenthesis of the `reinterpret_cast` has been placed after `length` when it should have been after `&buffer[index]`. At first I thought that this was an issue with the compiler (using VS2013) but after successfully compiling it using both VS2012 and gcc 4.6.3, I've come to the conclusion that this is for some reason allowed. The code won't run on either Windows or Linux as the length parameter is used as the pointer. So my question is why does this compile? Looking at the documentation of `reinterpret_cast` I can't find any documentation on it saying that you can pass a comma separated list of values to it and what it will do with it.

Original source