What's a portable way to implement no-op state

2019-01-20 07:32发布

One in a while there's a need for a no-op statement in C++. For example when implementing assert() which is disabled in non-debug configuration (also see this question):

#ifdef _DEBUG
#define assert(x) if( !x ) { \
                     ThrowExcepion(__FILE__, __LINE__);\
                  } else {\
                     //noop here \
                  }
#else
#define assert(x) //noop here
#endif

So far I'm under impression that the right way is to use (void)0; for a no-op:

(void)0;

however I suspect that it might trigger warnings on some compilers - something like C4555: expression has no effect; expected expression with side-effect Visual C++ warning that is not emitted for this particular case but is emitted when there's no cast to void.

Is it universally portable? Is there a better way?

标签: c++ noop
10条回答
一夜七次
2楼-- · 2019-01-20 07:57

I recommend using:

static_cast<void> (0)   
查看更多
太酷不给撩
3楼-- · 2019-01-20 07:59

And what about:

#define NOP() ({(void)0;})

or just

#define NOP() ({;})
查看更多
淡お忘
4楼-- · 2019-01-20 08:00
    inline void noop( ) {}

Self-documenting

查看更多
再贱就再见
5楼-- · 2019-01-20 08:02

AFAIK, it is universally portable.

#define MYDEFINE()

will do as well.

Another option may be something like this:

void noop(...) {}
#define MYDEFINE() noop()

However, I'd stick to (void)0 or use intrinsics like __noop

查看更多
登录 后发表回答