开发者

Unnamed parameters in C

In C, unlike C++, all parameters to a function definition must be named.

Instead of quashing "unused parameter" errors with (void)a, or openly using __attribute__((unused)), I've created the following macro:

#define UNUSED2(var, uniq) UNUSED_ ## line ## var __attribute((unused))
// squash unused variable warnings, can it be done without var?
#define UNUSED(var) UNUSED2(var, __func__)

Used like this

void blah(char const *UNUSED(path)) {}

Is there some way I can guarantee a unique "dummy" variable name (obviously LINE and __func__ can't cut it), or neglect to name the unused variables at all?

Update0

The final code used is avai开发者_JAVA技巧lable here.

#ifdef __cplusplus
    // C++ allows you to omit parameter names if they're unused
#   define OMIT_PARAM
#else
    // A variable name must be provided in C, so make one up and mark it unused
#   define OMIT_PARAM3(uniq) const omitted_parameter_##uniq VARATTR_UNUSED
#   define OMIT_PARAM2(uniq) OMIT_PARAM3(uniq)
#   define OMIT_PARAM OMIT_PARAM2(__COUNTER__)
#endif

#ifdef _MSC_VER
#   define VARATTR_UNUSED
#else
#   define VARATTR_UNUSED __attribute__((unused))
#endif

It's used like this:

void blah(char const *OMIT_PARAM) {}

And avoids both unused parameter, unnamed parameter warnings, and guarantees that it's not going to clobber some other variable name.


Stop looking for ugly non-portable, compiler-specific hacks. Even if the function does not use one of its arguments, presumably there's a reason the argument exists: to match a particular prototype/signature, most likely for the purpose of function pointer type compatibility. Assuming this is the case, the argument has a name determined by what the caller is expected to pass; the fact that your particular function is not using the argument for anything is largely irrelevant. So give it its proper name, and use __attribute__((unused)) if you insist on enabling this warning. I just always disable the unused argument warning because it's obviously bogus.


VC has a __COUNTER__ macro which gives uniqueness, it appears that GCC has an equivalent macro with the same name from version 4.3.5 (although I can't at the moment find a live link).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜