When you declare a function or a method with an argument that will not be used, the compiler emits a warning (if -Wunused-parameter is enabled in gcc and clang) about that issue.
See the code below:
#include <iostream>
#include <string>
void print_msg(const std::string& e)
{
std::cout << "Hello world\n";
}
int main()
{
print_msg("Friday");
return 0;
}
The g++ compiler output is;
In function 'void print_msg(const std::string&)':
<source>:4:35: warning: unused parameter 'e' [-Wunused-parameter]
4 | void print_msg(const std::string& e)
| ~~~~~~~~~~~~~~~~~~~^
It is a good idea to enable this compiler flag (-Wunused-parameter) to remove all unused parameters from your code, making it cleaner.
That could mean removing the parameter completely like below:
void print_msg();
or simply removing the variable name from the argument list:
void print_msg(const std::string& );
Why would you choose the latter instead of the former?
- You are sure you will use that parameter later, so you prefer keeping it to avoid modifying all the places where your function is called.
- You are overriding a method where the parameter is not used and you cannot modify the interface of the virtual method you are implementing.
- You want to catch an exception but do not want to do anything with the exception itself (probably you want to ignore the exception, log a message, or generate a more generic error code).
However, in some scenarios, you simply do not know if a variable will be used or not (e.g. conditional compilation based on #define and #ifdef preprocessor directives or template-based code).
Consider this example:
You have a log subsystem but want to enable it with the LOG_ENABLED preprocessor definition. This is its implementation:
void log_msg(const std::string& msg)
{
#ifdef LOG_ENABLED
std::cout << msg << "\n";
#else
// do nothing
#endif
}
int main()
{
log_msg("This is a something to log");
}
If the LOG_ENABLED definition is set, everything will work as expected, otherwise the “unused parameter” warning will occur.
Since it is a good idea to enable such warnings AND it is also a good idea to have your code as clean and expressive as possible, [[maybe_unused]] is the hero here.
[[maybe_unused]] is an attribute introduced in C++17 that is used to mark structs, classes, variables, arguments, enums, etc. as “probably unused”, so the compiler simply ignores if such symbols are not being used in the scope they are defined. Thus, apart from removing the warning, marking a variable as “maybe unused” is a nice way to self-document the code and the intentions behind the symbols you create.
Your program will look like this with this attribute:
#include <iostream>
#include <string>
void log_msg([[maybe_unused]] const std::string& msg)
{
#ifdef LOG_ENABLED
std::cout << msg << "\n";
#else
// do nothing
#endif
}
int main()
{
log_msg("This is a something to log");
}
More on this attribute here: https://en.cppreference.com/w/cpp/language/attributes/maybe_unused