Avoiding unused variables warnings when using assert() in a Release build

前端 未结 16 1802
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 09:10

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

int Result = Func();
assert( Result == 1 );
<
16条回答
  •  再見小時候
    2020-12-05 09:44

    You could create another macro that allows you to avoid using a temporary variable:

    #ifndef NDEBUG
    #define Verify(x) assert(x)
    #else
    #define Verify(x) ((void)(x))
    #endif
    
    // asserts that Func()==1 in debug mode, or calls Func() and ignores return
    // value in release mode (any braindead compiler can optimize away the comparison
    // whose result isn't used, and the cast to void suppresses the warning)
    Verify(Func() == 1);
    

提交回复
热议问题