【问题标题】:Warning C4101 unreferenced local variable警告 C4101 未引用的局部变量
【发布时间】:2019-11-27 06:53:58
【问题描述】:
void func(char * param)
{
#ifdef _XYZ_
.....somecode here using param
#endif
.....lots of code here not using param
}

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

【问题讨论】:

标签: c++ compiler-warnings


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    编译自:

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

    【讨论】:

      【解决方案3】:

      在 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
      }
      

      【讨论】:

        【解决方案4】:

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

        使用与discard result marked [[nodiscard]]相同的方法:

        除了强制转换为 void,鼓励编译器发出 警告。

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

        编译器不会产生任何额外的指令:)

        【讨论】:

        • 其实你在两个路径中都使用了参数所以编译器不会产生警告。
        • 是的,回答您的具体问题:I don't want warning
        • 但是显示的示例,在我不需要的地方也需要考虑。 :)
        • 您必须表达变量未被使用的“意图”,并且编译器不需要提醒您。您是否忘记了“这个”变量,它对这个问题的回答是/否。不要使用一些偷偷摸摸的解决方案来隐藏这个意图,其他开发者会因此而诅咒你。
        • 以上大多数答案可能有助于解决问题的多种解决方案。
        猜你喜欢
        • 1970-01-01
        • 2012-08-04
        • 2021-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-17
        • 1970-01-01
        相关资源
        最近更新 更多