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. The Lounge
  3. Programming Lesson of the Day

Programming Lesson of the Day

Scheduled Pinned Locked Moved The Lounge
c++question
44 Posts 21 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.
  • Richard DeemingR Richard Deeming

    Programming Lesson of the Day #3: Check your assumptions before posting them as a lesson! ;P

    bool x = true;
    bool y = false;
    (x & y).Dump(); // Output: False

    It's not commonly used, but for booleans, & is the non-short-circuiting version of &&. It's the C# equivalent of VB.NET's And, whereas && equates to AndAlso.

    & Operator (C# Reference)[^]:

    Binary & operators are predefined for the integral types and bool. ... For bool operands, & computes the logical AND of its operands; that is, the result is true if and only if both its operands are true. The & operator evaluates both operators regardless of the first one's value.


    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

    S Offline
    S Offline
    Slow Eddie
    wrote on last edited by
    #31

    Great tip and explanation. I am currently teaching myself C# and this is extremely helpful.

    A giraffe is a horse designed by a committee... ... or an Agile methodology...

    1 Reply Last reply
    0
    • K kdmote

      OK, my turn to learn something new: What's Dump()?

      J Offline
      J Offline
      James Curran
      wrote on last edited by
      #32

      `Dump()` is an extension method added to all objects within LinqPad. LinqPad is a tool which allows writing & compiling simple C# code snippets (plus a bunch of other things). (And the basic version is free: www.linqpad.com )

      Truth, James

      K 1 Reply Last reply
      0
      • J Jeremy Falcon

        Oh I hear ya man. I reckon the difference being the compiler knows that's an assignment operator. My understanding of the way C# and Java does things is to create an object where needed from literals / constants / expressions. So, it would be more like this...

        "Hello, world!".ToUpper()

        ...just instead of a string it's a false... which gets treated like a boolean.

        Jeremy Falcon

        J Offline
        J Offline
        James Curran
        wrote on last edited by
        #33

        No, it's the use of an int as a boolean that C# complains about. The assignment in the if() is fine, provided it's a boolean:

        bool x = false;

        if (x = true)
        "It's True".Dump();

        Truth, James

        1 Reply Last reply
        0
        • K kdmote

          OK, my turn to learn something new: What's Dump()?

          Richard DeemingR Offline
          Richard DeemingR Offline
          Richard Deeming
          wrote on last edited by
          #34

          It's an extension method provided by LINQPad[^]. EDIT: I'm sure James' response wasn't there when I posted this! :doh:


          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

          J 1 Reply Last reply
          0
          • OriginalGriffO OriginalGriff

            Programming Lesson of the Day #2: If you'd used C# it wouldn't have compiled ... :laugh:

            Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

            S Offline
            S Offline
            sasadler
            wrote on last edited by
            #35

            Heh, I'd like to use C# but as an embedded developer (using TI DSPs) it's not really an option for me. It's C/C++ or DSP assembly (which nobody in their right mind wants to do!!!!).

            1 Reply Last reply
            0
            • I irneb

              Jeremy Falcon wrote:

              I reckon the difference being the compiler knows that's an assignment operator.

              Nope, it's because both C# and Java are more type safe (strong typed) than C is. In this case they define a boolean type, C just interprets an integer to have similar "meaning" to a boolean. And the if statement (in C#/Java) requires a boolean input argument. It's the same sort of situation as sending a string into a function which expected a float - compiler error - wrong type. This is an example of where C uses a weak typing system. It generally just uses the raw data as if it's in the expected type. Effectively turning it into a raw type-cast. The more strongly typed languages disallow most of these, probably because they tend to be the reason behind lots of bugs (if not most).

              J Offline
              J Offline
              Jeremy Falcon
              wrote on last edited by
              #36

              Makes sense.

              Jeremy Falcon

              1 Reply Last reply
              0
              • J James Curran

                `Dump()` is an extension method added to all objects within LinqPad. LinqPad is a tool which allows writing & compiling simple C# code snippets (plus a bunch of other things). (And the basic version is free: www.linqpad.com )

                Truth, James

                K Offline
                K Offline
                kdmote
                wrote on last edited by
                #37

                :thumbsup:

                1 Reply Last reply
                0
                • OriginalGriffO OriginalGriff

                  And I've learned something today! Thank you - I didn't know that. :thumbsup:

                  Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

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

                  A massive recall of all existing code is being contemplated... Warning: "|" is also not the same as "||".

                  "(I) am amazed to see myself here rather than there ... now rather than then". ― Blaise Pascal

                  D 1 Reply Last reply
                  0
                  • Richard DeemingR Richard Deeming

                    It's an extension method provided by LINQPad[^]. EDIT: I'm sure James' response wasn't there when I posted this! :doh:


                    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                    J Offline
                    J Offline
                    James Curran
                    wrote on last edited by
                    #39

                    >

                    I'm sure James' response wasn't there when I posted this!

                    Well, at least you got the URL right....

                    Truth, James

                    1 Reply Last reply
                    0
                    • D den2k88

                      X & Y

                      is not the same as

                      X && Y

                      Twenty minutes wasted on a condition who refused to yield the correct result.

                      CALL APOGEE, SAY AARDWOLF GCS d--- s-/++ a- C++++ U+++ P- L- E-- W++ N++ o+ K- w+++ O? M-- V? PS+ PE- Y+ PGP t++ 5? X R++ tv-- b+ DI+++ D++ G e++>+++ h--- ++>+++ y+++*      Weapons extension: ma- k++ F+2 X If you think 'goto' is evil, try writing an Assembly program without JMP. -- TNCaver "Go ahead, make my day"

                      J Offline
                      J Offline
                      jcmaida
                      wrote on last edited by
                      #40

                      How this difference can hurt. m is length of string = 3; *b is first character in string say "xyz" while( *b & m-- ) { b++; } is not the same as while( *b && m-- ) {b++;} because while( *b & m-- ) { b++; } fails when *b is null tested AND m is decremented at the same time ergo m is off by 1 while( *b && m-- ) { b++; } fails when *b is null tested. m is not decremented because of the short circuit test of *b stops the evaluation ergo m has the correct character count so yes & and && are not the same so be careful of the logic when using C

                      1 Reply Last reply
                      0
                      • I irneb

                        Don't get me wrong ... I'm not dissing on C and saying C# is all that great. I was simply pointing out why the if statement would fail to even compile in this particular case when trying this in C#. You make a point where C#'s strong typing does make a programmer's life more cumbersome - you'd need to convert a byte array into specific types to do what you want, though there is readily available built-in libraries for that, or you could use an unsafe code block and use pointers to cast one into the other (just like you'd have done in C). Point is it would make for more coding to achieve the same thing. Though it's only in special circumstances (like your example) where this is beneficial. Nearly everywhere else it means there's less to think about (and guard against) due to the compiler checking types for you. If you find you constantly run into situations where you need to cast between types - then perhaps C# isn't the correct tool for the job and you'd be better off with C instead.

                        D Offline
                        D Offline
                        den2k88
                        wrote on last edited by
                        #41

                        I didn't get you wrong, neither I was dissing C# - each task has its tool for the job. For a graphical interface I would most definetely use C# (now I'm stuck to VB6 due to company decisions), and for almost any program. My job involves both hardware control and computation/memory heavy algorithms so C/C++ is the tool of excellence as of now.

                        CALL APOGEE, SAY AARDWOLF GCS d--- s-/++ a- C++++ U+++ P- L- E-- W++ N++ o+ K- w+++ O? M-- V? PS+ PE- Y+ PGP t++ 5? X R++ tv-- b+ DI+++ D++ G e++>+++ h--- ++>+++ y+++*      Weapons extension: ma- k++ F+2 X If you think 'goto' is evil, try writing an Assembly program without JMP. -- TNCaver "Go ahead, make my day"

                        1 Reply Last reply
                        0
                        • L Lost User

                          A massive recall of all existing code is being contemplated... Warning: "|" is also not the same as "||".

                          "(I) am amazed to see myself here rather than there ... now rather than then". ― Blaise Pascal

                          D Offline
                          D Offline
                          den2k88
                          wrote on last edited by
                          #42

                          Did I sort the "have I locked my car?" effect? ;P

                          CALL APOGEE, SAY AARDWOLF GCS d--- s-/++ a- C++++ U+++ P- L- E-- W++ N++ o+ K- w+++ O? M-- V? PS+ PE- Y+ PGP t++ 5? X R++ tv-- b+ DI+++ D++ G e++>+++ h--- ++>+++ y+++*      Weapons extension: ma- k++ F+2 X If you think 'goto' is evil, try writing an Assembly program without JMP. -- TNCaver "Go ahead, make my day"

                          1 Reply Last reply
                          0
                          • H Herbie Mountjoy

                            I find the strong typing of C# is more of a help than a hindrance. Back in my C days I would get into horrible tangles doing precisely what you are trying to do. An int is not a bool even though many programmers of the era would treat them alike. I still encounter data tables that have integers or even strings used as boolean values and it makes my skin crawl.

                            We're philosophical about power outages here. A.C. come, A.C. go.

                            D Offline
                            D Offline
                            den2k88
                            wrote on last edited by
                            #43

                            Sometimes the assumption makes code shorter but definetely not faster (optimizars take away all the fun) or elegant. In fact I stopped using them interchangeably a while ago, now I use integers as bools only when marshalling between different conventions or storing in exchangeable data structures - it allows me to fix the size of the data field without stumbling in the differences of bool type size between compilers and languages.

                            CALL APOGEE, SAY AARDWOLF GCS d--- s-/++ a- C++++ U+++ P- L- E-- W++ N++ o+ K- w+++ O? M-- V? PS+ PE- Y+ PGP t++ 5? X R++ tv-- b+ DI+++ D++ G e++>+++ h--- ++>+++ y+++*      Weapons extension: ma- k++ F+2 X If you think 'goto' is evil, try writing an Assembly program without JMP. -- TNCaver "Go ahead, make my day"

                            1 Reply Last reply
                            0
                            • D den2k88

                              No. Example 2 & 4 is 0 2 && is 1 (true) In that case I needed the first form as I was checking for a flag in a flag register, but mistakenly used the second form due to, well, being the most common (althought not so much in my field, which requires the management of a lot of driverless hardware).

                              CALL APOGEE, SAY AARDWOLF GCS d--- s-/++ a- C++++ U+++ P- L- E-- W++ N++ o+ K- w+++ O? M-- V? PS+ PE- Y+ PGP t++ 5? X R++ tv-- b+ DI+++ D++ G e++>+++ h--- ++>+++ y+++*      Weapons extension: ma- k++ F+2 X If you think 'goto' is evil, try writing an Assembly program without JMP. -- TNCaver "Go ahead, make my day"

                              K Offline
                              K Offline
                              Kirill Illenseer
                              wrote on last edited by
                              #44

                              That depends on the language. In a strongly typed language, 1 and true aren't the same because one is a number and true is a boolean. So 2&4 is 0 and 2&&4 is 0 as well, however the difference is in side effects. SomeFunc & SomeOtherFunc will execute both functions with their side-effets, SomeFunc && SomeOtherFunc will stop executing if SomeFunc returns false. PS: I am talking about C# here which is, unlike C and C++, a strongly-typed language.

                              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