警告:变量已设置,但未使用


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

我收到"prev_offset"的[-Wunused-but-set-variable]警告,除了在prev_offset = offset;后添加cout << prev_offset;之外,还有更好的方法可以解决它吗?任何答案都是赞赏的,提前感谢。

有几种方法可以解决这个问题。一种是放入一个虚拟语句,将变量转换为 (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;
}
}

最新更新