在发布版本中使用 assert() 时避免未使用的变量警告 [英] Avoiding unused variables warnings when using assert() in a Release build

查看:55
本文介绍了在发布版本中使用 assert() 时避免未使用的变量警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时局部变量仅用于在 assert() 中检查它,就像这样 -

Sometimes a local variable is used for the sole purpose of checking it in an assert(), like so -

int Result = Func();
assert( Result == 1 );

在发布版本中编译代码时,assert()s 通常被禁用,因此此代码可能会产生关于 Result 已设置但从未读取的警告.

When compiling code in a Release build, assert()s are usually disabled, so this code may produce a warning about Result being set but never read.

一个可能的解决方法是 -

A possible workaround is -

int Result = Func();
if ( Result == 1 )
{
    assert( 0 );
}

但是它需要太多的输入,对眼睛来说并不容易并且导致总是检查条件(是的,编译器可能会优化检查,但仍然如此).

But it requires too much typing, isn't easy on the eyes and causes the condition to be always checked (yes, the compiler may optimize the check away, but still).

我正在寻找一种替代方法来表达这个 assert() ,它不会导致警告,但仍然易于使用并避免更改 assert() 的语义.

I'm looking for an alternative way to express this assert() in a way that wouldn't cause the warning, but still be simple to use and avoid changing the semantics of assert().

(在此代码区域中使用 #pragma 禁用警告不是一个选项,降低警告级别以使其消失也不是一个选项......).

(disabling the warning using a #pragma in this region of code isn't an option, and lowering warning levels to make it go away isn't an option either...).

推荐答案

我们使用一个宏来专门指示什么时候没有使用:

We use a macro to specifically indicate when something is unused:

#define _unused(x) ((void)(x))

那么在您的示例中,您将:

Then in your example, you'd have:

int Result = Func();
assert( Result == 1 );
_unused( Result ); // make production build happy

这样 (a) 生产构建成功,并且 (b) 在代码中很明显,该变量按设计未被使用,而不是只是被遗忘了.这在不使用函数参数时特别有用.

That way (a) the production build succeeds, and (b) it is obvious in the code that the variable is unused by design, not that it's just been forgotten about. This is especially helpful when parameters to a function are not used.

这篇关于在发布版本中使用 assert() 时避免未使用的变量警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆