I have read, both on this site and elsewhere, that the recommended programming style for C++ is to avoid using C-style casts, and prefer the C++-style static_cast
, dynamic_cast
, reinterpret_cast
, and const_cast
. The reasons for this recommendation generally boil down to (1) the C++ casts are safer because they are more specific and limited in meaning, and (2) they are intentionally verbose and ugly because you should not be using them often in good C++ code. However, this reasoning doesn't make as much sense when it comes to calling C functions from my C++ code.
In my C++ projects I am often forced to call OS-level libraries that only have a C interface, such as the POSIX sockets library for network operations. These C functions often expect the caller to make several pointer casts, and if I stick to only C++-style casts my code becomes clunky and verbose. For example, my networking code is littered with function calls like this:
std::size_t message_size;
ssize_t bytes_read = recv(fd, reinterpret_cast<char*>(&message_size), sizeof(message_size), MSG_WAITALL);
I'm not gaining any safety from using C++ casts (since reinterpret_cast
doesn't really add any more compile-time checks than a C-style cast), and the ugliness of the code isn't alerting me to a problem - there's no way to use socket functions without casting.
In light of the interface mismatch between C and C++, would it be reasonable to use C-style casts when calling C functions that require casting? Or are C-style casts always bad practice, and I should just accept the extra code bloat when I need to call C functions?
static_casts
here andreinterpret_casts
there, you end up polluting...static_cast
orreinterpret_cast
to ever prevent problems, e.g., over a C-style cast.