There are a couple of questions with similar names on StackOverflow, such as this one and this one .etc
However, none of them answered the questions in my mind...
Problem Background:
I'm including a C header file in C++ code. The problematic C code is shown below:
// C header file
static inline bool post_request(const customer_t *requester, const void *packagevoid)
{
const pkg_req_t *pkg = packagevoid;
...
... // some other code
}
The compiler complained that:
/<project_path>/handler_util.h:250:26: error: invalid conversion from 'const void*' to 'const const pkg_req_t*' {aka 'const pkg_req_s*'} [-fpermissive]
const pkg_req_t *pkg = packagevoid;
^~~~~~~
I changed the conversion to explictly use static_cast
:
// C header file: fixed
static inline bool post_request(const customer_t *requester, const void *packagevoid)
{
#ifdef __cplusplus
const pkg_req_t *pkg = static_cast<const pkg_req_t*>(packagevoid);
#else
const pkg_req_t *pkg = packagevoid;
#endif
...
... // some other code
}
Questions:
const pkg_req_t *pkg = packagevoid;
--- why this is legal in C but giving error in C++?- Is static_cast an elegant solution in this case? --- I'm asking this question because it appears that
const_cast<pkg_req_t*>reinterpret_cast<const pkg_req_t*>
also works. Which one is better? - In the compilation error message, why is the compiler reporting "[-fpermissive]" in the end of the error message?