警告:变量集但未使用

时间:2017-09-09 07:29:11

标签: c++

T offset = ps->first, prev_offset;
bool first = true;

while (1) {
  if (first)
    first = false;
  else
    assert(offset > prev_offset);
  pl = l.find_inc(offset);
  prev_offset = offset;
  if (pl == l.m.end())
    break;
  while (ps != s.m.end() && ps->first + ps->second <= pl->first)
    ++ps;
  if (ps == s.m.end())
    break;
  offset = pl->first + pl->second;
  if (offset <= ps->first) {
    offset = ps->first;
    continue;
  }
}

//我得到了[-Wunused-but-set-variable]警告&#34; prev_offset&#34;,除了在cout << prev_offset;之后添加prev_offset = offset;之外,还有更好的解决方法吗?任何答案都表示赞赏,提前谢谢。

1 个答案:

答案 0 :(得分:0)

有几种方法可以解决这个问题。一种是放入一个将变量强制转换为(void)的伪声明。

(void) prev_offset; // this should stop the warning.

另一个是有条件地包含变量,其方式与assert()根据是否设置NDEBUG宏有条件地包含其检查的方式类似。

// When you use ASSERT_CODE() the code only appears in debug builds
// the same as the assert() checks. That code is removed in 
// release builds.

#ifndef NDEBUG
#define ASSERT_CODE(code) code
#else
#define ASSERT_CODE(code)
#endif

// ...


T offset = ps->first;
ASSERT_CODE(T prev_offset); // give it its own line
bool first = true;

while (1) {
  if (first)
    first = false;
  else
    assert(offset > prev_offset);
  pl = l.find_inc(offset);

  ASSERT_CODE(prev_offset = offset); 

  if (pl == l.m.end())
    break;
  while (ps != s.m.end() && ps->first + ps->second <= pl->first)
    ++ps;
  if (ps == s.m.end())
    break;
  offset = pl->first + pl->second;
  if (offset <= ps->first) {
    offset = ps->first;
    continue;
  }
}
相关问题