I am working on a project that uses select from C++ code. The code uses the macros FD_ZERO, FD_SET, FD_ISSET etc. Unfortunately These macros use ‘C’ casts, ergo they generate compiler warnings when the code is compiled with -Wold-style-cast. What is the best way for disabling -Wold-style-cast just for these macros?
The only options I can think of are:
- Use
#pragma diagnosticto disable the warning for the functions using macros - wrap the macro calls in an inline function and disable the warning around the function.
Does anyone have a better approach?
I use select and those macros in C++ code with -Wall and get no warnings, though I do not use -Wold-style-cast. I think a better approach would be to take a step back and reconsider why it is important to not use C-style casts. I think, for interfacing with C standard library functions, it is entirely appropriate.
The C++
dynamic_castmethod is useful for polymorphism and classes.const_castis a special case for removing const-ness.static_castand C’s(type)casts are very similar. I am not sure what advantage usingstatic_cast<type>provides over(type)casts, except that it is in the C++ style.reinterpret_cast<type>offers little advantage over C’s*(type*)&cast method, and is about as ugly as they come.In general, the need for casting implies a certain weakness in the design of software, though
dynamic_castis arguably an exception to this. While it is commendable to strive to not need casts in one’s own code, I don’t think there is much value in trying to retroactively apply these values to third-party libraries, especially standard or OS ones.If you really don’t want to use C-style casts in your code, I would set a policy outside of the compiler settings and just review your code and remove them. If you really want to have the compiler do this work for you, then you’ll have to disable the warning for software you can’t control. This may be more work than it is worth, and in some cases is not even necessary. On Darwin, for instance, FD_ISSET has no casts in its implementation. There are, after all, far worse practices than C-style casts to banish from code.