警告 C4101 未引用的局部变量

Warning C4101 unreferenced local variable

void func(char * param)
{
#ifdef _XYZ_
.....somecode here using param
#endif
.....lots of code here not using param
}

编译出错,我不想在代码中出现警告。

很简单。如果 _XYZ_NOT 定义的变量 param 未在函数中使用,编译器发出可以转换为:

翻译自编译器:

My friend you asked me for a piece of memory named param but you are not using it. Are you sure this is intended?

从 C++17 开始,我们有 maybe_unused attribute 来抑制对未使用实体的警告:

void func([[maybe_unused]] char * param)
{
#ifdef _XYZ_
.....somecode here using param
#endif
}

在 C++17 的 [[maybe_unused]] 属性之前,您可以使用特定于编译器的命令。

在 MSVC 中,您可以这样做:

#pragma warning(push)
#pragma warning(disable:4101)
void func(char * param)
{
#ifdef _XYZ_
.....somecode here using param
#endif
}
#pragma warning(pop)

在Borland/Embarcadero中,您可以这样做:

#pragma argsused
void func(char * param)
{
#ifdef _XYZ_
.....somecode here using param
#endif
}

在 GCC 中,您可以使用其中之一:

void func(__attribute__((unused)) char * param)
{
#ifdef _XYZ_
.....somecode here using param
#endif
}
void func(__unused char * param)
{
#ifdef _XYZ_
.....somecode here using param
#endif
}
void func([[gnu::unused]] char * param)
{
#ifdef _XYZ_
.....somecode here using param
#endif
}

或者,您可以简单地引用参数而不使用任何特定于编译器的技巧:

void func(char * param)
{
#ifdef _XYZ_
.....somecode here using param
#else
(void)param;
#endif
}

怎么样:static_cast<void>(param);

使用与 discard result marked [[nodiscard]]:

相同的方法

other than a cast to void, the compiler is encouraged to issue a warning.

[[nodiscard]] bool is_good_idea();

void func(char * param)
{
#ifdef _XYZ_
  .....somecode here using param
#else
  // suppress warning:
  static_cast<void>(param);
#endif

  // also valid:
  static_cast<void>(is_good_idea());
}

编译器不会生成任何附加指令:)