Wunused-but-set-variable warning treatment

混江龙づ霸主 提交于 2019-12-07 04:58:55

问题


I have the following code, and while compiling it with gcc-4.6 I get warning:

warning: variable ‘status’ set but not used [-Wunused-but-set-variable]

#if defined (_DEBUG_)
#define ASSERT       assert
#else                           /* _DEBUG_ */
#define ASSERT( __exp__ )
#endif   

static inline void cl_plock(cl_plock_t * const p_lock)
{
        status_t status;
        ASSERT(p_lock);
        ASSERT(p_lock->state == INITIALIZED);

        status = pthread_rwlock_unlock(&p_lock->lock);
        ASSERT(status == 0); 
}

When _DEBUG_ flag isn't set I get the warning. Any ideas how can I workaround this warning?


回答1:


You can change your ASSERT macro to:

#if defined (_DEBUG_)
#define ASSERT       assert
#else                           /* _DEBUG_ */
#define ASSERT( exp ) ((void)(exp))
#endif   

If the expression has no sideeffects, then it should still be optimised out, but it should also suppress the warning (if the expression does have side-effects, then you would get different results in debug and non-debug builds, which you don't want either!).




回答2:


The compiler option to turn off unused variable warnings is -Wno-unused. To get the same effect on a more granular level you can use diagnostic pragmas like this:

int main()
{
  #pragma GCC diagnostic ignored "-Wunused-variable"
  int a;
  #pragma GCC diagnostic pop
  // -Wunused-variable is on again
  return 0;
}

This is, of course, not portable but you can use something similar for VS.




回答3:


You could surround the variable declaration of status with a #ifdef clause.

#ifdef _DEBUG_
    status_t status
#endif

EDIT: You have to surround the call also:

#ifdef _DEBUG_
    status = pthread_rwlock_unlock(&p_lock->lock);
#else
    pthread_rwlock_unlock(&p_lock->lock);
#endif

or you can switch off the error message.



来源:https://stackoverflow.com/questions/6583237/wunused-but-set-variable-warning-treatment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!