Why does C# && and || operators work the way they do?

前端 未结 7 1989
余生分开走
余生分开走 2020-12-06 14:25

here is a tl;dr

I come from a C++ background. && is suppose to check if left side is true and right side is true. what does & have anything to do with th

7条回答
  •  伪装坚强ぢ
    2020-12-06 14:50

    A perhaps overlooked part of the question here is why doesn't C# automatically cast integers to booleans?

    Automatically casting ints to bools (using the rules of C/C++) allow for a accidentally assigning instead of comparing two values. The C# language designers probably wanted to avoid this...

    int a, b;
    if(a == b)
        { /* They are equal, so execute this code... */ }
    
    if(a = b)
        { /* Were they actually equal? Dunno, but they are now... */ }
    

    or

    while(a = b)
        { /* Eternal loop */ }
    

提交回复
热议问题