Is it ok to use bitwise operator in place of a logical operator like OR

后端 未结 4 677
失恋的感觉
失恋的感觉 2021-01-26 23:55

This may be stupid.but i have a simple doubt Suppose i have the following check in a function

bool Validate(string a , string b)
{
    if(a == null || b == null)         


        
4条回答
  •  心在旅途
    2021-01-27 00:31

    In boolean expressions (rather than integers etc), the main difference is: short-circuiting. || short-circuits. | does not. In most cases you want short-circuiting, so || is much much more common. In your case, it won't matter, so || should probably be used as the more expected choice.

    The times it matters is:

    if(politics.IsCeasefire() | army.LaunchTheRockets()) {
        // ...
    }
    

    vs:

    if(politics.IsCeasefire() || army.LaunchTheRockets()) {
        // ...
    }
    

    The first always does both (assuming there isn't an exception thrown); the second doesn't launch the rockets if a ceasefire was called.

提交回复
热议问题