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

后端 未结 4 674
失恋的感觉
失恋的感觉 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:35

    In this case (with bool arguments) the | operator is not a bitwise operator. It's just a non-short-circuiting version of the logical or(||).

    The same goes for & vs. && - it's just a non-short-circuiting version of logical and.

    The difference can be seen with side-effects, for example in

    bool Check()
    {
        Console.WriteLine("Evaluated!");
        return true;
    }
    
    // Short-circuits, only evaluates the left argument.
    if (Check() || Check()) { ... }
    
    // vs.
    
    // No short circuit, evaluates both.
    if (Check() | Check()) { ... }
    

提交回复
热议问题