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

后端 未结 5 1510
一整个雨季
一整个雨季 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:18

    Take into account what are you going to process

    If it is a boolean, the results are pretty clear:

    if (!false)   // If false TRUE
    if (false==0) // If false TRUE
    

    If it is an integer, pay attention to the ! condition

    if (0==0) // Unexpected behaviors are missing..
    
    if (!-1) // False
    if (! 0) // True
    if (! 1) // False
    

    For chars both conditions give me the same results:

    if (! ' ')  // nothing
    if (' '==0) // nothing
    
    if (! 'z')  // nothing
    if ('z'==0) // nothing
    

提交回复
热议问题