Condition checking: if(x==0) vs. if(!x)

后端 未结 5 1500
一整个雨季
一整个雨季 2020-12-30 17:52

What\'s the differences of if(x==0) vs. if(!x)? Or are they always equivalent? And for different C++ build-in types of x:

5条回答
  •  温柔的废话
    2020-12-30 18:09

    if(!x)

    is "if x is not false", that means that in order to evaluate that, you might have to cast x to a bool.

    >> This can be harmful and if you wish to avoid it you should use something like the Safe Bool Idiom


    if(x!=0)

    means "if x is not 0", so that is evaluated comparing x to 0. That might also involve an implicit conversion.

    >> Be careful when using pointers this way, C++11 introduces a nullptr to avoid the confusion of NULL==0 (semantically different): What exactly is nullptr?

提交回复
热议问题