Auto cast to void unused variable C++ - c++

I am trying to solve huge number of warnings in a C++ project that is generated by a lot of unused variables. For example, consider this function:
void functionOne(int a, int b)
{
// other stuff and implementations :D
doSomethingElse();
runProcedureA();
}
In my project, in order to surpress the warnings I am simply casting the unused variables to void because I cannot change the methods signatures.
void functionOne(int a, int b)
{
(void)a;
(void)b;
// other stuff and implementations :D
doSomethingElse();
runProcedureA();
}
This technique works all right but I have a really huge quantity of functions that I need to do this in order to solve the warnings issue. Is there any way to auto refactor all these functions by casting all unused parameters to void?
Currently, I am working with CLion IDE and VSCODE.

A simple alternative is to not give names for the parameters instead of the cast. This way the unusage would be considered intentional:
void functionOne(int, int)
Another way to achieve the same is:
void functionOne([[maybe_unused]] int a, [[maybe_unused]] int b)
Is there any way to auto refactor all these functions
Potential XY-problem: If you don't want to be warned about unused parameters, how about disabling the warning?

Related

How would you write feature agnostic code for both AVX2 and AVX512?

One way of doing this would be to create function pointers which conditionally point to different functions depending upon a preprocessor directive which selects the desired feature set.
#if defined(__AVX512__)
void (*func_ptr)() = _mm512_func;
#else
void (*func_ptr)() = _mm256_func;
#endif
int main()
{
func_ptr();
return 0;
}
Are there better ways of doing this? Thanks.
If you're detecting AVX512 only at compile time, you don't need function pointers.
The simplest way: don't define different names for the same function at all, just select which definition to compile in the .cpp file where you have multiple versions of it. That keeps the compile-time dispatching isolated to the file that defines the function, not visible to the rest of your code.
#ifdef __AVX512F__
void func(float *__restrict a, float *__restrict b) {
... // AVX512 version here
}
#elif defined(__AVX2__) && defined(__FMA__)
void func(float *__restrict a, float *__restrict b) { // same name
... // AVX2 version here
}
#else
... // SSE2 or scalar fallback
#endif
Although for testing you do probably want to be able to build all versions of it and test + benchmark them against each other, so you might consider using #define func _mm512_func, or using some preprocessor tricks inside that one file. Maybe another answer will have a better idea for this.
I thought function pointers were preferred over macros in the C++ community. But this does the same job
Maybe if the function point is void (*static const func_ptr)() then you can count on it being inlined / optimized away. You really don't want to add extra overhead for dispatching if you don't need it (e.g. for runtime CPU detection, setting functions pointers in an init function that runs cpuid)

Pc Lint, how to suppress err 613(Possible use of null ponter) for class with init()

Tried to simplify the situation as much as possible. So I have a class:
class C
{
int * field;
public:
C() : field(nullptr) {}
void init(int* f) { field = f; }
int getI1() { return *field; }
int getI2() { return *field; }
};
which generates 2 Lint warnings 613 (Possible use of null pointer 'C::i'...)
I know that "field" won't be null when getI1() or getI2() are called. And unfortunately I cannot initialize it in constructor. So I want to suppress Lint warnings. I can do it like this
class C
{
int * field;
public:
C() : field(nullptr) {}
void init(int* f) { field = f; }
int getI1() { return *field; } //lint !e613
int getI2() { return *field; } //lint !e613
};
but in my real case:
1) There are rather many such classes and each class has many
functions that use this pointer.
2) My managements doesn't allow me to add too many lint
comments in the code.
So my question: does anyone know a command-line option that will let me tell Lint "I know the code is not best, just stop checking this particular member variable for null"?
Something similar to -sem parameter, maybe?
So my question: does anyone know a command-line option that will let me tell Lint "I know the code is not best, just stop checking this particular member variable for null"?
That's the wrong way to handle it (even if I knew such command line parameter).
PC-Lint warns you correctly about that
int getI1() { return *i; } //lint !e613
int getI2() { return *i; } //lint !e613
may unintentionally dereference a nullptr.
Just trying to suppress1 that waning isn't a very good idea, since the call of the init() function isn't mandatory.
The correct way to get rid of it is to add an explicit check like
int getI1() {
if(i) {
return *i;
}
throw std::runtime_error("i wasn't initialized properly.");
}
1) There are rather many such classes and each class has many functions that use this pointer.
There's no other way than just wading through them and refactor that bad code.
2) My managements doesn't allow me to add too many lint comments in the code.
That's a good policy. They spent the money to install the SCA tool for reasons, and want the code being improved.
If that collides with the time you've got available doing so, ask them to establish a task that allows you to accomplish that.
If you just want to concentrate on other (more important stuff) reported by PC-Lint, use grep or alike tools to filter out what you don't want to see ATM. But don't establish a command line parameters to suppress them completely. That are things that will be forgotten forever and never be touched or approached at later stages again.
1
Suppressing any errors or warnings given by a SCA tool like PC-Lint defeats the whole purpose of it, unless you're absolutely sure the tool gives you a false positive. Otherwise your company could simply save the money spent for the licenses, and stick to the bad coding habits.
It seems that after the constructor has run, you have an instance that is not usable (will crash if you call getT1() or getT2()). That's not something that I like at all.
Much better to have a constructor C(int* f). Problem goes away. This is a case where the warning is entirely justified and warns you of bad code, so the bad code should be fixed.
I know that code is bad, should be fixed and so on. Unfortunately I cannot do it right now (because of huge amount of effort for one person and highly risky changes), but those errors were overwhelming other, sometimes more critical, problems
I found out that to suppress this warning in one line you can do:
-esym(613, C::field)

Bad practice to call static function from external file via function pointer?

Consider the following code:
file_1.hpp:
typedef void (*func_ptr)(void);
func_ptr file1_get_function(void);
file1.cpp:
// file_1.cpp
#include "file_1.hpp"
static void some_func(void)
{
do_stuff();
}
func_ptr file1_get_function(void)
{
return some_func;
}
file2.cpp
#include "file1.hpp"
void file2_func(void)
{
func_ptr function_pointer_to_file1 = file1_get_function();
function_pointer_to_file1();
}
While I believe the above example is technically possible - to call a function with internal linkage only via a function pointer, is it bad practice to do so? Could there be some funky compiler optimizations that take place (auto inline, for instance) that would make this situation problematic?
There's no problem, this is fine. In fact , IMHO, it is a good practice which lets your function be called without polluting the space of externally visible symbols.
It would also be appropriate to use this technique in the context of a function lookup table, e.g. a calculator which passes in a string representing an operator name, and expects back a function pointer to the function for doing that operation.
The compiler/linker isn't allowed to make optimizations which break correct code and this is correct code.
Historical note: back in C89, externally visible symbols had to be unique on the first 6 characters; this was relaxed in C99 and also commonly by compiler extension.
In order for this to work, you have to expose some portion of it as external and that's the clue most compilers will need.
Is there a chance that there's a broken compiler out there that will make mincemeat of this strange practice because they didn't foresee someone doing it? I can't answer that.
I can only think of false reasons to want to do this though: Finger print hiding, which fails because you have to expose it in the function pointer decl, unless you are planning to cast your way around things, in which case the question is "how badly is this going to hurt".
The other reason would be facading callbacks - you have some super-sensitive static local function in module m and you now want to expose the functionality in another module for callback purposes, but you want to audit that so you want a facade:
static void voodoo_function() {
}
fnptr get_voodoo_function(const char* file, int line) {
// you tagged the question as C++, so C++ io it is.
std::cout << "requested voodoo function from " << file << ":" << line << "\n";
return voodoo_function;
}
...
// question tagged as c++, so I'm using c++ syntax
auto* fn = get_voodoo_function(__FILE__, __LINE__);
but that's not really helping much, you really want a wrapper around execution of the function.
At the end of the day, there is a much simpler way to expose a function pointer. Provide an accessor function.
static void voodoo_function() {}
void do_voodoo_function() {
// provide external access to voodoo
voodoo_function();
}
Because here you provide the compiler with an optimization opportunity - when you link, if you specify whole program optimization, it can detect that this is a facade that it can eliminate, because you let it worry about function pointers.
But is there a really compelling reason not just to remove the static from infront of voodoo_function other than not exposing the internal name for it? And if so, why is the internal name so precious that you would go to these lengths to hide that?
static void ban_account_if_user_is_ugly() {
...;
}
fnptr do_that_thing() {
ban_account_if_user_is_ugly();
}
vs
void do_that_thing() { // ban account if user is ugly
...
}
--- EDIT ---
Conversion. Your function pointer is int(*)(int) but your static function is unsigned int(*)(unsigned int) and you don't want to have to cast it.
Again: Just providing a facade function would solve the problem, and it will transform into a function pointer later. Converting it to a function pointer by hand can only be a stumbling block for the compiler's whole program optimization.
But if you're casting, lets consider this:
// v1
fnptr get_fn_ptr() {
// brute force cast because otherwise it's 'hassle'
return (fnptr)(static_fn);
}
int facade_fn(int i) {
auto ui = static_cast<unsigned int>(i);
auto result = static_fn(ui);
return static_cast<int>(result);
}
Ok unsigned to signed, not a big deal. And then someone comes along and changes what fnptr needs to be to void(int, float);. One of the above becomes a weird runtime crash and one becomes a compile error.

Static Library; Unused Symbols; Definitions in Header

I'm creating an HAL for an embedded system and part of that is re-creating printf functionality (via a class called Printer). Because it is an embedded system, code-space is critical and I would like to exclude floating-point support in printf by default, but allow the user of my HAL to include it on a project-by-project basis without having to recompile my library.
All of my classes have their method definitions inline in the header file.
printer.h looks something like....
class Printer {
public:
Printer (const PrintCapable *printCapable)
: m_printCapable(printCapable) {}
void put_char (const char c) { ... }
#ifdef ENABLE_PRINT_FLOAT
void put_float (const float f) { ... }
#endif
void printf (const char fmt[], ...) {
// Stuffs...
#ifdef ENABLE_PRINT_FLOAT
// Handle floating point support
#endif
}
private:
const PrintCapable *m_printCapable;
}
// Make it very easy for the user of this library to print by defining an instance for them
extern Printer out;
Now, it is my understanding that this should work great.
printer.cpp is nice and simple:
#include <printer.h>
#include <uart/simplexuart.h>
const SimplexUART _g_simplexUart;
const Printer out(&_g_simplexUart);
Unnecessary code bloat:
If I compile my library with and project without ENABLE_PRINT_FLOAT defined, then code size is 9,216 kB.
Necessary code bloat:
If I compile both library and project with ENABLE_PRINT_FLOAT, code size is 9,348 kB.
Necessary code blo.... oh wait, it's not bloated:
If I compile the project with and the library without ENABLE_PRINT_FLOAT, I would expect to see the same as above. But no... instead I have code size of 7,092 kB and a program that doesn't execute correctly.
Minimum Size:
If I compile both are compiled without ENABLE_PRINT_FLOAT, then the code size is only 6,960 kB.
How can I achieve my goal of small code size, flexible classes, and easy-to-use?
Build system is CMake. Full project source is here.
Main file is nice and simple:
#include <printer.h>
void main () {
int i = 0;
while (1) {
out.printf("Hello world! %u %05.2f\n", i, i / 10.0);
++i;
delay(250); // 1/4 second delay
}
}
If you have different definition of inline functions in different translation units you have undefined behavior. Since your printf() definition changes with the setting of the ENABLE_PRINT_FLOAT macro you just see this effect.
Typically the compiler won't inline functions if it considers them too complicated. It would create out of line implementations and pick a random one when linking. Since the are all the same picking a random is OK ... oh wait, they are different and the program may be broken.
You could make floating point support a template parameter of your printf() function: the function would be called using
out.printf<false>("%d\n", i);
out.printf<true>("%f", f);
The implementation of printf() would delegate to suitable internal functions (to have the compiler merge definitions where they are identical) with the floating point support being disabled for the false case: it could do nothing, fail, or assert.
It may be simpler not do any conditional support in the first place and rather use a stream-like interface: since the formatting functions for the different types are separate, only those actually being used are picked up.
If it is an option for you library to use C++11 you could use variadic template to deal with the situation: the individual formatter would be implemented as separate functions which are dispatched to inside printf(): this way there is no printf() function which needs to handle all formatting. Instead, only the type formatters needed would be pulled in. The implementation could look something like this:
inline char const* format(char const* fmt, int value) {
// find format specifier and format value accordingly
// then adjust fmt to point right after the processed format specifier
return fmt;
}
inline char const* format(char const* fmt, double value) {
// like the other but different
}
// othe formatters
inline int printf(char const* fmt) { return 0; }
template <typename A, typename... T>
inline int printf(char const* fmt, A&& arg, T&& args) {
fmt = format(fmt, std::forward<A>(arg));
return 1 + printf(fmt, std::forward<T>(args));
)
Clearly, there are different approaches how common code between different formatter can be factored out. However, the overall idea should work. Ideally, the generic code would do as little work as possible to have the compiler merge all non-trivial code between the different uses. As a nice side-effect this implementation could make sure that the format specifiers are matching the objects being passed and either produce a suitable error or appropriately handle the format in some way.

Avoid warning 'Unreferenced Formal Parameter'

I have a super class like this:
class Parent
{
public:
virtual void Function(int param);
};
void Parent::Function(int param)
{
std::cout << param << std::endl;
}
..and a sub-class like this:
class Child : public Parent
{
public:
void Function(int param);
};
void Child::Function(int param)
{
;//Do nothing
}
When I compile the sub-class .cpp file, I get this error
warning C4100: 'param' : unreferenced formal parameter
As a practice, we used to treat warnings as errors. How to avoid the above warning?
Thanks.
In C++ you don't have to give a parameter that you aren't using a name so you can just do this:
void Child::Function(int)
{
//Do nothing
}
You may wish to keep the parameter name in the declaration in the header file by way of documentation, though. The empty statement (;) is also unnecessary.
I prefer using a macro, as it tells not only the compiler my intention, but other maintainers of the code, and it's searchable later on.
The method of commenting out the argument name can easily be missed by people unfamiliar with the code (or me 6 months later).
However, it's a style-issue, neither method is "better" or more optimal with regards to code generated, performance or robustness. To me, the deciding factor is informing others of my intent through a standardized system. Omitting the parameter name and putting in a comment would work equally well:
void CFooBar::OnLvnItemchanged(NMHDR *pNMHDR, LRESULT *pResult)
{
UNREFERENCED_PARAMETER(pNMHDR);
Alternatively:
void CFooBar::OnLvnItemchanged(NMHDR* /* pNMHDR */, LRESULT *pResult)
{
// Not using: pNMHDR
I would say that the worst solution is suppressing the warning message; that that will affect your entire file or project, and you'll lose the knowledge that maybe you've missed something. At least by adding the macro, or commenting out the argument name, you've told others that you've made a conscious decision to not use this argument and that it's not a mistake.
The Windows SDK in WinNT.h defines UNREFERENCED_PARAMETER() along with DBG_UNREFERENCED_PARAMETER() and DBG_UNREFERENCED_LOCAL_VARIABLE(). They all evaluate to the same thing, but the difference is that DBG_UNREFERENCED_PARAMETER() is used when you are starting out and expect to use the parameter when the code is more complete. When you are sure you'll never use the parameter, use the UNREFERENCED_PARAMETER() version.
The Microsoft Foundation Classes (MFC) have a similar convention, with the shorter UNUSED() and UNUSED_ALWAYS() macros.
Pick a style and stick with it. That way later on you can search for "DBG_UNREFERENCED_PARAMETER" in your code and find any instances of where you expected to use a argument, but didn't. By adopting a consistent style, and habitually using it, you'll make it easier for other and yourself later on.
Another technique that you can use if you want to keep the parameter name is to cast to void:
void Child::Function(int param)
{
(void)param; //Do nothing
}
As #Charles Bailey mentioned, you can skip the parameter name.
However, in certain scenarios, you need the parameter name, since in debug builds you are calling an ASSERT() on it, but on retail builds it's a nop. For those scenarios there's a handy macros (at least in VC++ :-)) UNREFERENCED_PARAMETER(), which is defined like this:
#define UNREFERENCED_PARAMETER(x) x
Note that the simple cast #R Samuel Klatchko posted also works, but I personally find it more readable if the code is explicit that this is an unreferenced parameter vs. simple unexplained cast like that.
Pragma works nicely too since it's clear you are using VS. This warning has a very high noise to benefit ratio, given that unreferenced parameters are very common in callback interfaces and derived methods. Even teams within Microsoft Windows who use W4 have become tired of its pointlessness (would be more suitable for /Wall) and simply added to their project:
#pragma warning(disable: 4100)
If you want to alleviate the warning for just a block of code, surround it with:
#pragma warning(push)
#pragma warning(disable: 4100)
void SomeCallbackOrOverride(int x, float y) { }
#pragma warning(pop)
The practice of leaving out the parameter name has the downside in the debugger that you can't easily inspect by name nor add it to the watch (becomes confused if you have more than one unreferenced parameter), and while a particular implementation of a method may not use the parameter, knowing its value can help you figure out which stage of a process you are in, especially when you do not have the whole call stack above you.
Since C++17 you also can use [[maybe_unused]] to avoid such warnings:
class Parent
{
public:
virtual void Function([[maybe_unused]] int param);
};
I would use a macro to suppress the unreferenced formal parameter warning:
#define UNUSED( x ) ( &reinterpret_cast< const int& >( x ) )
This has the following advantages:
Unlike #define UNUSED( x ) ( void )x, it doesn't introduce a need for the full definition of the parameter's type to be seen where no such need may have existed before.
Unlike #define UNUSED( x ) &x, it can be used safely with parameters whose types overload the unary & operator.
What about just adding reference with a comment:
void Child::Function(int param)
{
param; //silence unreferenced warning
}
This was also suggested here: https://learn.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-level-4-c4100?view=vs-2019