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

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

问题描述

有时,局部变量仅用于在assert()中检查它。

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

在Release版本中编译代码时,assert()通常被禁用,



可能的解决方法是 -

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

但它需要太多的打字,不容易的眼睛和原因



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



(禁用使用#pragma的警告在这个区域的代码不是一个选项,并降低警告级别,使其消失不是一个选择...)。

解决方案

我们使用宏来明确指出未使用时:

  #define _unused(x)然后在你的例子中,你会有:

$($ void)($ void)(x))
$ b

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



这样(a)生产生成成功,在代码中显而易见的是,变量未被设计未使用,而不是刚刚被遗忘。这在不使用函数的参数时尤其有用。


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

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

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).

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().

(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

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天全站免登陆