首页 > 解决方案 > 修复 -Werror=unused-but-set-variable

问题描述

这可能是一个愚蠢的问题,但如果不添加打印语句,我将无法解决这个问题。

这是我的代码

        double best_mother_index = 0;
        double best_mother_energy = -9999;
        double best_mother_plane = -99;

        for(size_t p=0; p< marks_mother_vector.size(); p++)
        {
           art::Ptr<simb::MCParticle> mother = marks_mother_vector[p];
           std::vector<double> mother_energy_recod = marks_mother_energy_fraction_map[mother];

           if( mother_energy_recod[0] > best_mother_energy){
                best_mother_index = p;
                best_mother_energy = mother_energy_recod[0];
                best_mother_plane = 0;
           }
           if (mother_energy_recod[1] > best_mother_energy){
                best_mother_index = p;
                best_mother_energy = mother_energy_recod[1];
                best_mother_plane = 1;
           }
           if( mother_energy_recod[2] > best_mother_energy){
                best_mother_index = p;
                best_mother_energy = mother_energy_recod[2];
                best_mother_plane = 2;
           }
        }

i get the following error message when compiling

:9: error: variable ‘best_mother_plane’ set but not used [-Werror=unused-but-set-variable]
  double best_mother_plane = -99;

为什么这是唯一有问题的变量?我该如何解决这个问题?

标签: c++compilation

解决方案


为什么这是唯一有问题的变量?

因为这是唯一设置但未使用的变量。

我该如何解决这个问题?

任何一个:

  • 将变量的值用于某事。考虑一下您希望该值如何影响程序的行为。
  • 或者,如果您不打算使用该变量,则将其完全删除。
  • 从技术上讲,您可以使用 [[maybe_unused]] 声明变量,但在这种简单情况下,上述选项之一可能会更好。在使用宏来控制条件编译(用于移植到不同的系统)时,它最有用。
  • 当编译器注意到此类未使用的变量时,您可以避免告诉编译器编译失败。上面提到的选项之一会更好,因为这样的变量通常表示一个错误,这使得这个警告很有价值。

推荐阅读