【问题标题】:Warning when using - binary operator in C++ to take away int from variable. What is the cause?在 C++ 中使用 - 二元运算符从变量中删除 int 时发出警告。原因是什么?
【发布时间】:2015-04-16 13:07:49
【问题描述】:

我有一个函数,它有一个整数作为形式参数:

string function1(int hundreds)
{
// some code
else if (hundreds > 9)
{ 
    hundreds - 5;
}

当我编译这段代码时,我在二进制减号运算符处收到一条警告消息,上面写着“未使用的表达式结果”。是什么导致抛出此警告消息?

我的猜测是,减去一个常量整数不是一个好习惯,相反,我应该定义一个类型为 const int 的变量,其值为 5,并将其从 hundreds 中取走。即我应该使用而不是hundreds - 5

const int DEDUCTION = 5;
//code up to the following statement
hundreds - DEDUCTION;

【问题讨论】:

  • 您得到“表达式结果未使用”,因为未使用数百 - 5 的结果。你想做什么?数百 = 数百 - 5; (或等价于数百 -= 5;)
  • hundreds - 5; 这没有任何作用——这个语句没有副作用。你的意思是hundreds -= 5;
  • @IgorTandetnik 这正是我的意思 :) 抱歉,这是漫长的一天。我应该删除这个问题。

标签: c++ arithmetic-expressions


【解决方案1】:

因为hundreds - 5 什么都不做。这就像写if ( hundreds > 9 ) { 1; }

【讨论】:

    【解决方案2】:

    您应该将结果分配给另一个变量或将其分配回hundreds -= 5;。否则,结果将被简单地丢弃。

    【讨论】:

      【解决方案3】:

      由于未使用算术减法的结果,因此您会收到相应的警告。 您关于用 const int 替换数字 5 的假设是不正确的,因为这并不能消除警告的原因。

      【讨论】:

      • “二元运算符”表示接受两个参数的运算符;这是二进制减号,参数是hundreds5
      猜你喜欢
      • 2018-03-17
      • 1970-01-01
      • 2010-11-21
      • 2014-07-01
      • 1970-01-01
      • 2012-01-10
      • 2022-01-08
      • 1970-01-01
      • 2014-11-14
      相关资源
      最近更新 更多