Why '&&' and not '&'?

前端 未结 16 1519
别跟我提以往
别跟我提以往 2020-11-27 12:11

Why is && preferable to & and || preferable to |?

I asked someone who\'s been programming for years a

16条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 13:12

    OK, on face value

        Boolean a = true;
        Boolean b = false;
    
        Console.WriteLine("a({0}) && b({1}) =  {2}", a, b, a && b);
        Console.WriteLine("a({0}) || b({1}) =  {2}", a, b, a || b);
        Console.WriteLine("a({0}) == b({1}) =  {2}", a, b, a == b);
    
        Console.WriteLine("a({0}) & b({1}) =  {2}", a, b, a & b);
        Console.WriteLine("a({0}) | b({1}) =  {2}", a, b, a | b);
        Console.WriteLine("a({0}) = b({1}) =  {2}", a, b, a = b);
    

    produce the same answer. However, as you showed, if you have a more complex question so:

    if (a and b and c and d) ..
    

    If a is not true and maybe b is a function where it has to go off, connect to something, get this, do that, make a decision.. why bother? Waste of time, you know it's already failed. Why make the machine go off and do extra pointless work?

    I've always used && because I put the most likely to fail first, ergo, less calculations before moving on when there is no point. If there is no way to predict less likely choices, such as you have a boolean to limit output of data, something like:

    if (limit && !MyDictionary.ContainsKey("name")) 
        continue;
    

    If it's not limit, don't bother checking for the key, which could take longer..

提交回复
热议问题