警告 C4101 未引用的局部变量

Warning C4101 unreferenced local variable

本文关键字:局部变量 引用 C4101 警告      更新时间:2023-10-16
void func(char * param)
{
#ifdef _XYZ_
.....somecode here using param
#endif
.....lots of code here not using param
}

编译出错,即使在代码中我也不想发出警告。

自 C++17 以来,我们有了maybe_unused属性来抑制对未使用实体的警告:

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

很简单。如果未定义_XYZ_则函数中不使用变量param,并且编译器会发出可以转换为的衰减:

译自编译者:

我的朋友,你问我要一段名叫param的记忆,但你是 不使用它。你确定这是故意的吗?

在 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);

使用同样用于丢弃标记为[[nodiscard]]的结果的相同方法:

除了强制转换到无效之外,鼓励编译器发出 警告。

[[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());
}

编译器不会生成任何其他指令:)