Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

Portable UNUSED parameter macro used on function signature for C and C++

I'm interested in creating a macro for eliminating the unused variable warning.

This question describes a way to suppress the unused parameter warning by writing a macro inside the function code:

Universally compiler independent way of implementing an UNUSED macro in C/C++

But I'm interested in a macro that can be used in the function signature:

void callback(int UNUSED(some_useless_stuff)) {}

This is what I dug out using Google (source)

#ifdef UNUSED
#elif defined(__GNUC__)
# define UNUSED(x) UNUSED_ ## x __attribute__((unused))
#elif defined(__LCLINT__)
# define UNUSED(x) /*@unused@*/ x
#elif defined(__cplusplus)
# define UNUSED(x)
#else
# define UNUSED(x) x
#endif

Can this be further expanded for other compilers?

Edit: For those who can't understand how tagging works: I want a solution for both C and C++. That is why this question is tagged both C and C++ and that is why a C++ only solution is not acceptable.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The way I do it is like this:

#define UNUSED(x) (void)(x)
void foo(const int i) {
    UNUSED(i);
}

I've not had a problem with that in Visual Studio, Intel, gcc and clang.

The other option is to just comment out the parameter:

void foo(const int /*i*/) {
  // When we need to use `i` we can just uncomment it.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...