Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Other Discussions
  3. The Weird and The Wonderful
  4. Logic

Logic

Scheduled Pinned Locked Moved The Weird and The Wonderful
comhelpquestion
56 Posts 24 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • F Fabio V Silva

    Again, you're wrong, they are both logical operators in that case but one is short-circuited and the other is not! You have the same think in VB with the And, AndAlso, Or, OrElse operators, they are all handy in different situations.

    L Offline
    L Offline
    Lost User
    wrote on last edited by
    #17

    Please read the msdn links that you posted, VB is different and C# is different. VB has two logical operators for AND operation, And does not short-circuit and AndAlso short-circuits. This is a design decision for backward compatibility with VB6. But C# was designed from the ground-up, so the designers were not constrained by the need to be backward compatible, they had more freedom which made them design && to always short-circuit. Read this link which CLEARLY states that & and && are different: http://blog.dmbcllc.com/2009/03/16/vs-and-vs-whats-the-difference/[^] If you're still not convinced, then good luck to you, this is my last reply to this post.

    F 1 Reply Last reply
    0
    • L Lost User

      Please read the msdn links that you posted, VB is different and C# is different. VB has two logical operators for AND operation, And does not short-circuit and AndAlso short-circuits. This is a design decision for backward compatibility with VB6. But C# was designed from the ground-up, so the designers were not constrained by the need to be backward compatible, they had more freedom which made them design && to always short-circuit. Read this link which CLEARLY states that & and && are different: http://blog.dmbcllc.com/2009/03/16/vs-and-vs-whats-the-difference/[^] If you're still not convinced, then good luck to you, this is my last reply to this post.

      F Offline
      F Offline
      Fabio V Silva
      wrote on last edited by
      #18

      What you don't seem to realise is that I'm not talking about the operators names but what they do. From MSDN[^]: & - logical AND | - logical OR && - conditional AND || - conditional OR From MSDN[^]: The operation x && y corresponds to the operation x & y except that if x is false, y is not evaluated (because the result of the AND operation is false no matter what the value of y may be). This is known as "short-circuit" evaluation. Which means I was right in my first post to say there was no difference, in that if condition, to use one or the other, the program still runs with no exceptions and as expected. Your only argument so far is that one is called logical and the other bitwise which doesn't change the fact that I was right; call them what you want.

      L 1 Reply Last reply
      0
      • F Fabio V Silva

        What you don't seem to realise is that I'm not talking about the operators names but what they do. From MSDN[^]: & - logical AND | - logical OR && - conditional AND || - conditional OR From MSDN[^]: The operation x && y corresponds to the operation x & y except that if x is false, y is not evaluated (because the result of the AND operation is false no matter what the value of y may be). This is known as "short-circuit" evaluation. Which means I was right in my first post to say there was no difference, in that if condition, to use one or the other, the program still runs with no exceptions and as expected. Your only argument so far is that one is called logical and the other bitwise which doesn't change the fact that I was right; call them what you want.

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #19

        This is true only in case where the operands of & are both bool, but unlike && which takes only bool operands, & can also take int as operands which can lead to unexpected behavior.

        F 1 Reply Last reply
        0
        • L Lost User

          This is true only in case where the operands of & are both bool, but unlike && which takes only bool operands, & can also take int as operands which can lead to unexpected behavior.

          F Offline
          F Offline
          Fabio V Silva
          wrote on last edited by
          #20

          And what's the case on the line of code in my first post?

          L 1 Reply Last reply
          0
          • F Fabio V Silva

            I just got an answer[^] downvoted in Q&A because I used & instead of && in this line:

            if(UsernameTextBox.Text == "Manager" & PasswordTextBox.Text == "Maintenance")

            I'm still waiting for a response to my "Why?"

            A Offline
            A Offline
            AspDotNetDev
            wrote on last edited by
            #21

            This should really mess with your noggin:

            bool isTrue = true || true && false; // True
            bool isFalse = true | true && false; // False.

            Also, given your example, I'd prefer the double ampersand for 2 reasons: 1) for short-circuiting and 2) for standards' sake.

            [Managing Your JavaScript Library in ASP.NET]

            F Q 2 Replies Last reply
            0
            • A AspDotNetDev

              This should really mess with your noggin:

              bool isTrue = true || true && false; // True
              bool isFalse = true | true && false; // False.

              Also, given your example, I'd prefer the double ampersand for 2 reasons: 1) for short-circuiting and 2) for standards' sake.

              [Managing Your JavaScript Library in ASP.NET]

              F Offline
              F Offline
              Fabio V Silva
              wrote on last edited by
              #22

              I was just discussing the case that someone said that line was incorrect and downvoted my answer when in reality I just copied the OP's line and changed the = to == which is what was actually stopping it from working as expected. I prefer the double ampersand as well as a standard, the same way I always try to use short circuiting in VB which doesn't seem to be common practice, at least in online samples and articles.

              1 Reply Last reply
              0
              • F Fabio V Silva

                And what's the case on the line of code in my first post?

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #23

                Your case is an exception, don't treat it like a rule.

                M 1 Reply Last reply
                0
                • F Fabio V Silva

                  I just got an answer[^] downvoted in Q&A because I used & instead of && in this line:

                  if(UsernameTextBox.Text == "Manager" & PasswordTextBox.Text == "Maintenance")

                  I'm still waiting for a response to my "Why?"

                  _ Offline
                  _ Offline
                  _Erik_
                  wrote on last edited by
                  #24

                  In the case you have posted the final result would be the same as if you had used the && operator. There is, however, an important difference between & and &&. Have a look at this example:

                  ICollection col = null;
                  if (col != null && col.Count > 0)
                  // Whatever

                  This would first check this expression: col != null; like it is false and we are using && operator, it would not even try to check the second operand, becouse the final result will be false. However, if we use just the bitwise & operator:

                  ICollection col = null;
                  if (col != null & col.Count > 0)
                  // Whatever

                  Since & operator is a bitwise operator it will try to check both operands so, in this case, it would throw a NullReferenceException when trying to evaluate the result of the second operand. That is why we always use the && operator in our boolean expressions, placing each operand in the right place. I guess this is what others have been trying to explain to you in this thread. That said, I would not have downvoted your answer just for this if the rest of the answer is correct, and I think that not being able to make you understand this is not reason enough to tell them to RTFM.

                  F 1 Reply Last reply
                  0
                  • _ _Erik_

                    In the case you have posted the final result would be the same as if you had used the && operator. There is, however, an important difference between & and &&. Have a look at this example:

                    ICollection col = null;
                    if (col != null && col.Count > 0)
                    // Whatever

                    This would first check this expression: col != null; like it is false and we are using && operator, it would not even try to check the second operand, becouse the final result will be false. However, if we use just the bitwise & operator:

                    ICollection col = null;
                    if (col != null & col.Count > 0)
                    // Whatever

                    Since & operator is a bitwise operator it will try to check both operands so, in this case, it would throw a NullReferenceException when trying to evaluate the result of the second operand. That is why we always use the && operator in our boolean expressions, placing each operand in the right place. I guess this is what others have been trying to explain to you in this thread. That said, I would not have downvoted your answer just for this if the rest of the answer is correct, and I think that not being able to make you understand this is not reason enough to tell them to RTFM.

                    F Offline
                    F Offline
                    Fabio V Silva
                    wrote on last edited by
                    #25

                    Again, what makes you think I don't know the difference between & and &&?! I never said they do the same thing and I do know that && is the most commonly used. That, however, does not make it wrong to use & between two boolean and it does not invalidate the fact that in that case it makes no difference. And if someone says it does then they should RTFM!

                    _ K N S 4 Replies Last reply
                    0
                    • F Fabio V Silva

                      Again, what makes you think I don't know the difference between & and &&?! I never said they do the same thing and I do know that && is the most commonly used. That, however, does not make it wrong to use & between two boolean and it does not invalidate the fact that in that case it makes no difference. And if someone says it does then they should RTFM!

                      _ Offline
                      _ Offline
                      _Erik_
                      wrote on last edited by
                      #26

                      Fabio V Silva wrote:

                      what makes you think I don't know the difference between & and &&?!

                      Oh, nothing at all but, you know, this is a public forum, and although there are many posts in this thread none of them was giving a good explanation about the differencies between those operators, becouse there are differencies, I know them, you know them and I know you know them, but a beginner might get confused after reading this thread. That's all.

                      1 Reply Last reply
                      0
                      • F Fabio V Silva

                        So, are you saying you can't use & in that case?! They do the same except for the fact that && is short-circuited.

                        K Offline
                        K Offline
                        Keith Barrow
                        wrote on last edited by
                        #27

                        Fabio V Silva wrote:

                        They do the same except for the fact that && is short-circuited.

                        Except they don't do they? For boolean operands they do the same thing, (ignoring, as you said, the short circuiting which is a very good reason to use &&). Take this example:

                        Console.WriteLine( 42 && 3);

                        Syntax error. Why? Because it is a Logical Operator which takes booleans as its operands. Now take:

                        Console.WriteLine( 42 & 3)</pre>
                        Answer 2: Why? Because it is a Bitwise Logical Operator (though most people drop the "Logical") ANDing on the bits:

                        101010 AND
                        000011

                        000010

                        = 2.

                        The bitwise | and & operators are best left for work at the bit-level (such as bit-masking), whereas the the C# logical operators are better suited to boolean comparisons, like in the OP.

                        I wouldn't have voted you down BTW, but I would have pointed it out.

                        Sort of a cross between Lawrence of Arabia and Dilbert.[^]
                        -Or-
                        A Dead ringer for Kate Winslett[^]

                        1 Reply Last reply
                        0
                        • F Fabio V Silva

                          Again, what makes you think I don't know the difference between & and &&?! I never said they do the same thing and I do know that && is the most commonly used. That, however, does not make it wrong to use & between two boolean and it does not invalidate the fact that in that case it makes no difference. And if someone says it does then they should RTFM!

                          K Offline
                          K Offline
                          Keith Barrow
                          wrote on last edited by
                          #28

                          http://www.codeproject.com/feature/HallOfSHame.aspx?msg=3895520#xx3895520xx[^]

                          Sort of a cross between Lawrence of Arabia and Dilbert.[^]
                          -Or-
                          A Dead ringer for Kate Winslett[^]

                          L 1 Reply Last reply
                          0
                          • G gumi_r msn com

                            Really? And I always thought that '&&' was simply a short-circuited '&'. I must go RTFM. :sigh:

                            0 Offline
                            0 Offline
                            0bx
                            wrote on last edited by
                            #29

                            Ha, that's what they taught me as well. It's utter nonsense off course since both '&' and '|' would be completely useless if that was the only difference. It's just that it's a good habit to always use '&&' and '||' unless you need '&' or '|' specifically, even in cases where the result is the same.

                            1 Reply Last reply
                            0
                            • L Lost User

                              As I have stated in my reply to Fabio, & and && are for different purpose. & is a bitwise operator and && is a logical operator, they may produce same output in certain situations, but it does not mean that you can use them interchangeably. In C#, logical operators always short-circuit. See this link for an example: http://blog.dmbcllc.com/2009/03/16/vs-and-vs-whats-the-difference/[^]

                              G Offline
                              G Offline
                              gumi_r msn com
                              wrote on last edited by
                              #30

                              The && operator should be used instead of the & operator for clarity's sake because its the standard way of doing things. Also the && operator gives you some type safety that the & operator does not when dealing with LOGICAL ANDS: (4 && 5) will not compile but (4 & 5) will. If you are intending to perform a LOGICAL AND operation you could end up performing a LOGICAL BITWISE AND operation instead by mistake. But in any case, the reason you are giving: "(...)In C#, logical operators always short-circuit(...) is so wrong I dont even know where to begin. The operator & is an overloadable operator. Integral and boolean types have their own predefined & binary operators: &(int, int) computes the logical bitwise AND of its operands while &(bool, bool) computes the logical AND of its operands; that is, the result is true if and only if both its operands are true. This is all straight from the C# specifications:http://msdn.microsoft.com/en-us/library/sbf85k1c.aspx[^] So bool & bool is NOT A BITWISE OPERATION at all. Its a normal LOGICAL AND OPERATION where both terms are always evaluated contrary to bool && bool where the second term is evaluated if and only if the first term is true.

                              modified on Thursday, May 19, 2011 5:55 AM

                              1 Reply Last reply
                              0
                              • K Keith Barrow

                                http://www.codeproject.com/feature/HallOfSHame.aspx?msg=3895520#xx3895520xx[^]

                                Sort of a cross between Lawrence of Arabia and Dilbert.[^]
                                -Or-
                                A Dead ringer for Kate Winslett[^]

                                L Offline
                                L Offline
                                Lost User
                                wrote on last edited by
                                #31

                                forget it Keith, it's not gonna make any difference, I'm afraid you've just opened a can of worms.

                                1 Reply Last reply
                                0
                                • F Fabio V Silva

                                  Again, what makes you think I don't know the difference between & and &&?! I never said they do the same thing and I do know that && is the most commonly used. That, however, does not make it wrong to use & between two boolean and it does not invalidate the fact that in that case it makes no difference. And if someone says it does then they should RTFM!

                                  N Offline
                                  N Offline
                                  Nagy Vilmos
                                  wrote on last edited by
                                  #32

                                  Fabio V Silva wrote:

                                  in that case it makes no difference

                                  Wrong. Take notes if you like:

                                  A && B

                                  In this scenario A is evaluated and if it is true then B is evaluated and that is the result, otherwise the result is false and B never gets evaluated.

                                  A & B

                                  Both A and B are evaluated and the values are then combined using a Bitwise And operation, the output of which is cast to a Boolean for the result. At any level, these are two very diferent operations.

                                  Fabio V Silva wrote:

                                  And if someone says it does then they should RTFM!

                                  Manual read and understood, I still says it does.


                                  Panic, Chaos, Destruction. My work here is done. or "Drink. Get drunk. Fall over." - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre Have a bit more patience with newbies. Of course some of them act dumb -- they're often *students*, for heaven's sake. -- (Terry Pratchett, alt.fan.pratchett)

                                  G 1 Reply Last reply
                                  0
                                  • L Lost User

                                    Your case is an exception, don't treat it like a rule.

                                    M Offline
                                    M Offline
                                    musefan
                                    wrote on last edited by
                                    #33

                                    So are you admitting you were wrong?

                                    I may or may not be responsible for my own actions

                                    1 Reply Last reply
                                    0
                                    • N Nagy Vilmos

                                      Fabio V Silva wrote:

                                      in that case it makes no difference

                                      Wrong. Take notes if you like:

                                      A && B

                                      In this scenario A is evaluated and if it is true then B is evaluated and that is the result, otherwise the result is false and B never gets evaluated.

                                      A & B

                                      Both A and B are evaluated and the values are then combined using a Bitwise And operation, the output of which is cast to a Boolean for the result. At any level, these are two very diferent operations.

                                      Fabio V Silva wrote:

                                      And if someone says it does then they should RTFM!

                                      Manual read and understood, I still says it does.


                                      Panic, Chaos, Destruction. My work here is done. or "Drink. Get drunk. Fall over." - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre Have a bit more patience with newbies. Of course some of them act dumb -- they're often *students*, for heaven's sake. -- (Terry Pratchett, alt.fan.pratchett)

                                      G Offline
                                      G Offline
                                      gumi_r msn com
                                      wrote on last edited by
                                      #34

                                      Jesus, why do people pretend to know the absolute truth about things without even bothering to do some minimal research. What you are stating is completely wrong. The & operator is an OVERLOADABLE operator. As such, it has predefined behaviours for integral types and boolean types. (int & int) IS NOT THE SAME AS bool & bool. The first performs a logical bitwise AND operation while the latter performs a LOGICAL AND operation. There is no bitwise operation at all if the operator is dealing with two booleans. It is exactly the same as bool && bool except that both terms are evaluated no matter what the first expression evaluates to. If you are not convinced then please read the following MSDN C# reference link: http://msdn.microsoft.com/en-us/library/sbf85k1c.aspx[^] or better yet: http://msdn.microsoft.com/en-us/library/2a723cdk.aspx[^]

                                      _ N N 3 Replies Last reply
                                      0
                                      • G gumi_r msn com

                                        Jesus, why do people pretend to know the absolute truth about things without even bothering to do some minimal research. What you are stating is completely wrong. The & operator is an OVERLOADABLE operator. As such, it has predefined behaviours for integral types and boolean types. (int & int) IS NOT THE SAME AS bool & bool. The first performs a logical bitwise AND operation while the latter performs a LOGICAL AND operation. There is no bitwise operation at all if the operator is dealing with two booleans. It is exactly the same as bool && bool except that both terms are evaluated no matter what the first expression evaluates to. If you are not convinced then please read the following MSDN C# reference link: http://msdn.microsoft.com/en-us/library/sbf85k1c.aspx[^] or better yet: http://msdn.microsoft.com/en-us/library/2a723cdk.aspx[^]

                                        _ Offline
                                        _ Offline
                                        _Erik_
                                        wrote on last edited by
                                        #35

                                        Come on, guys. Stop this mess, ok? I don't pretend to know the absolute truth about this but, man, you are wrong or, at least, you might be confusing beginners. The fact that, as you say, "both terms are evaluated no matter what the first expression evaluates to" with the & operator is the key, and it is not a trivial difference. See this example:

                                        string s = null;
                                        bool b1 = s != null && s.Length == 0;
                                        bool b2 = s != null & s.Length == 0;

                                        You see the operands here are boolean expressions. However, while b1 would be assigned false without any problem, a runtime NullReferenceException would be thrown when trying to assing the value to b2. This is a really important difference. Both operands are not the same and can never be considered as if they were the same. Under some circumstances they can return the same result, yes, but that does not mean that they are exactly the same or that you can use any of them when you use boolean expressions. Can we, please, go on with our lifes now?

                                        OriginalGriffO 1 Reply Last reply
                                        0
                                        • G gumi_r msn com

                                          Jesus, why do people pretend to know the absolute truth about things without even bothering to do some minimal research. What you are stating is completely wrong. The & operator is an OVERLOADABLE operator. As such, it has predefined behaviours for integral types and boolean types. (int & int) IS NOT THE SAME AS bool & bool. The first performs a logical bitwise AND operation while the latter performs a LOGICAL AND operation. There is no bitwise operation at all if the operator is dealing with two booleans. It is exactly the same as bool && bool except that both terms are evaluated no matter what the first expression evaluates to. If you are not convinced then please read the following MSDN C# reference link: http://msdn.microsoft.com/en-us/library/sbf85k1c.aspx[^] or better yet: http://msdn.microsoft.com/en-us/library/2a723cdk.aspx[^]

                                          N Offline
                                          N Offline
                                          Nathan D Cook
                                          wrote on last edited by
                                          #36

                                          I'm just a novice programmer and didn't even realize (or I forgot?) that & was a legal command. I've always just used &&. I'm so confused by the last 30 some posts, I'm going to keep it simple and make sure I never use &.

                                          OriginalGriffO 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups