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. Do you not understand booleans?

Do you not understand booleans?

Scheduled Pinned Locked Moved The Weird and The Wonderful
data-structuresquestionannouncement
65 Posts 30 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.
  • A alanevans

    This stuff drives me up the wall!!!

    bool is_queue_empty(void)
    {
    if (queue_length==0)
    {
    return true;
    }
    else
    {
    return false;
    }
    }

    Or this:

    bool counter_zero = counter==0 ? true : false;

    Or this:

    if (isUDPSetup()==true)
    {
    if ((forceSend==false))
    {
    ...
    }
    }

    (Variable names have been changed to protect the guilty) Or this *New one*:

    void setNeedsUpdate(bool update)
    {
    if ((update==true))
    NeedsUpdate=true;
    else
    NeedsUpdate=false;
    }

    C Offline
    C Offline
    Clive D Pottinger
    wrote on last edited by
    #54

    I fully agree. This kind of stuff makes the code SO hard to read. And so many people do this too - just look at all the examples you were able to find! Atrocious. When will people learn to put spaces around their operators !?!?! :cool:

    Clive Pottinger Victoria, BC

    1 Reply Last reply
    0
    • M Member 3687319

      And I think your reasoning would be wrong. It IS more clear to write if (X==true). Just because you don't like it does not mean it is not more clear, especially to junior programmers. I am the senior lead and I instruct ALL of our programmers under me to write if (X==true). It doesn't cost the compiler anything and it makes it understandable by even the junior most person quickly. It is all about proper maintenance and thinking about the coder behind you instead of just yourself. X is a variable so comparing it like another variable is both consistent and readable.

      R Offline
      R Offline
      RoelofDeVilliers
      wrote on last edited by
      #55

      Why do boolean variables exist? To store and retrieve boolean expressions (TRUTH values). They were invented SO THAT we can write code like

      if (X)

      otherwise we could just as well remove the boolean type and work with integer flags like

      if (X==1)

      This was one of the issues people had with C. No proper boolean type. But now we have a proper boolean type so don't reduce it to a "flag value" that needs to be compared to something to find the truth. It holds the truth all on its own. That's its job.

      1 Reply Last reply
      0
      • A alanevans

        This stuff drives me up the wall!!!

        bool is_queue_empty(void)
        {
        if (queue_length==0)
        {
        return true;
        }
        else
        {
        return false;
        }
        }

        Or this:

        bool counter_zero = counter==0 ? true : false;

        Or this:

        if (isUDPSetup()==true)
        {
        if ((forceSend==false))
        {
        ...
        }
        }

        (Variable names have been changed to protect the guilty) Or this *New one*:

        void setNeedsUpdate(bool update)
        {
        if ((update==true))
        NeedsUpdate=true;
        else
        NeedsUpdate=false;
        }

        J Offline
        J Offline
        John Hunley
        wrote on last edited by
        #56

        Just ran across this in code I've been asked to maintain (no kidding):

        if (((ucGlobalHeaterEnable & (1 << UC_BHOSE_HTR_ON) ) > 0) ? 1 : 0)
        {
        ...
        }

        Unbelievable!

        Y 1 Reply Last reply
        0
        • A alanevans

          This stuff drives me up the wall!!!

          bool is_queue_empty(void)
          {
          if (queue_length==0)
          {
          return true;
          }
          else
          {
          return false;
          }
          }

          Or this:

          bool counter_zero = counter==0 ? true : false;

          Or this:

          if (isUDPSetup()==true)
          {
          if ((forceSend==false))
          {
          ...
          }
          }

          (Variable names have been changed to protect the guilty) Or this *New one*:

          void setNeedsUpdate(bool update)
          {
          if ((update==true))
          NeedsUpdate=true;
          else
          NeedsUpdate=false;
          }

          J Offline
          J Offline
          Jeroen De Dauw
          wrote on last edited by
          #57

          A true classic. I got thought to not do this first weeks in programming class, before learning stuff like functions.

          Jeroen De Dauw (blog | Twitter | Identi.ca)

          1 Reply Last reply
          0
          • Y YvesDaoust

            Wouldn't this be more run-time efficient, as the value of update can be cached in a register ?

            void setNeedsUpdate(bool update)
            {
            if (update == true)
            {
            NeedsUpdate= update;
            }
            else
            {
            NeedsUpdate= update;
            }
            }

            ;->

            B Offline
            B Offline
            BloodyBaron
            wrote on last edited by
            #58

            Or more straightforward:

            void setNeedsUpdate(bool update)
            {
            NeedsUpdate = update;
            }

            Less confusing, and same behavior.

            Y 1 Reply Last reply
            0
            • B BloodyBaron

              Or more straightforward:

              void setNeedsUpdate(bool update)
              {
              NeedsUpdate = update;
              }

              Less confusing, and same behavior.

              Y Offline
              Y Offline
              YvesDaoust
              wrote on last edited by
              #59

              What about this:

              void setNeedsUpdate(bool update)
              {
              // Case anaylsis
              if (update == (update == update))
              {
              // When update is true, flag the Update as Needed
              NeedsUpdate= update;
              }
              else if (update == (update != update))
              {
              // Else when update is false, flag the Update as not Needed
              NeedsUpdate= update;
              }
              else
              {
              // Else, when update is neither true nor false, assign an arbitrary value
              NeedsUpdate= update;
              }
              }

              it has the advantage of using no constant at all and cleanly handles the case where update is not a boolean value. I have added enlightening comments.

              1 Reply Last reply
              0
              • P patbob

                They were probable taught to program by some CS grad student who'd never done much significant real-world coding. That's right along the lines of the kinds of stupidity my teachers would teach us when I was an undergrad. Like everybody else, I picked up the stupidity too.. which lasted until I saw the other way and had to debug code to a schedule that was broken by such nonsense. I still do the compare to NULL sometimes, but I believe the C standard now defines NULL pointers as a false boolean value, so it is redundant and I'm trying to retrain away from it. Besides, boost smart pointers, which we use a lot in our code, have an override to generate a bool result for just such kinds of pointer checks and make comparing the raw pointer to NULL harder.

                We can program with only 1's, but if all you've got are zeros, you've got nothing.

                Y Offline
                Y Offline
                YvesDaoust
                wrote on last edited by
                #60

                Personally, I don't promote the C rule that implicitly turns an expression to boolean based on zeroness, whatever the type. Because even though perfectly legal it looks like a quick & dirty shorthand to spare typing a comparison; and it can overload an identifier with two meanings, that of the numerical value (or address) and that of a condition, as if the variable had two data types. What would you think of this (fiddled) snippet:

                int NoRetries; // Number of sending retries
                NoRetries= SendMessage();
                if (NoRetries)
                {
                // Investigate
                }

                as opposed to

                if (NoRetries > 0)
                {
                // Investigate
                }

                C was lacking a boolean type in the old days, in my opinion a design flaw. That made the aforementioned rule perfectly relevant. I prefer making the booleans explicit and highlighted. In a moderatly pedantic style, this would give us

                bool Retried= NoRetries > 0;
                if (Retried)
                {
                // Investigate
                }

                P 1 Reply Last reply
                0
                • N Nunnenkamp

                  void setNeedsUpdate(bool update)
                  {
                  if ((update==true))
                  NeedsUpdate=true;
                  else
                  NeedsUpdate=false;
                  }

                  This would be better if they returned it too. Nothing like getting back what you put into it.

                  bool setNeedsUpdate(bool update)
                  {
                  if ((update==true))
                  NeedsUpdate=true;
                  else
                  NeedsUpdate=false;
                  return NeedsUpdate;
                  }

                  Y Offline
                  Y Offline
                  YvesDaoust
                  wrote on last edited by
                  #61

                  Excellent, in addition this provides a way to test that assignment succeeded and was correct. I would even suggest

                  bool setNeedsUpdate(bool update)
                  {
                  if ((update==true))
                  {
                  NeedsUpdate=true;
                  return NeedsUpdate;
                  }
                  else
                  {
                  NeedsUpdate=false;
                  return NeedsUpdate;
                  }
                  }

                  so that if the code has a logic flaw, the function never returns ! ;)

                  1 Reply Last reply
                  0
                  • J John Hunley

                    Just ran across this in code I've been asked to maintain (no kidding):

                    if (((ucGlobalHeaterEnable & (1 << UC_BHOSE_HTR_ON) ) > 0) ? 1 : 0)
                    {
                    ...
                    }

                    Unbelievable!

                    Y Offline
                    Y Offline
                    YvesDaoust
                    wrote on last edited by
                    #62

                    Rather indigestible indeed. I couldn't resist rewriting this piece using bit fields (in my opinion a sadly underused feature in C):

                    struct tGlobalHeaterEnable
                    {
                    bool bHoseHtrOn: 1;

                    // More fields here...
                    

                    } sGlobalHeaterStatus;

                    if (sGlobalHeaterEnable.bHoseHtrOn)
                    {
                    // More code here...
                    }

                    1 Reply Last reply
                    0
                    • Y YvesDaoust

                      Personally, I don't promote the C rule that implicitly turns an expression to boolean based on zeroness, whatever the type. Because even though perfectly legal it looks like a quick & dirty shorthand to spare typing a comparison; and it can overload an identifier with two meanings, that of the numerical value (or address) and that of a condition, as if the variable had two data types. What would you think of this (fiddled) snippet:

                      int NoRetries; // Number of sending retries
                      NoRetries= SendMessage();
                      if (NoRetries)
                      {
                      // Investigate
                      }

                      as opposed to

                      if (NoRetries > 0)
                      {
                      // Investigate
                      }

                      C was lacking a boolean type in the old days, in my opinion a design flaw. That made the aforementioned rule perfectly relevant. I prefer making the booleans explicit and highlighted. In a moderatly pedantic style, this would give us

                      bool Retried= NoRetries > 0;
                      if (Retried)
                      {
                      // Investigate
                      }

                      P Offline
                      P Offline
                      patbob
                      wrote on last edited by
                      #63

                      I absolutely agree with you and consider using the a-zero-int-value-is-a-bool-false feature of C/C++ to be sloppy. Valid, but sloppy. I consider it sloppy because 0 is a meaningful (and highly useful) value for an int. However, with pointers, NULL is a meaningful value that indicates the pointer points to nothing, all other values are considered valid pointers. Using a pointer like a bool and checking if it is explicitly NULL are the same -- they are both asking if it points to anything. There is no other possible semantic interpretation. Writing code that omits an explicit comparison to NULL is also more easier to upgrade if the pointer is switched to one of the boost smart pointer classes, something we've done a fair amount of over the years. Not that the compiler doesn't catch the now-invalid comparison, but then you have to touch all that code just to get the same semantic meaning.

                      We can program with only 1's, but if all you've got are zeros, you've got nothing.

                      Y 1 Reply Last reply
                      0
                      • A alanevans

                        This stuff drives me up the wall!!!

                        bool is_queue_empty(void)
                        {
                        if (queue_length==0)
                        {
                        return true;
                        }
                        else
                        {
                        return false;
                        }
                        }

                        Or this:

                        bool counter_zero = counter==0 ? true : false;

                        Or this:

                        if (isUDPSetup()==true)
                        {
                        if ((forceSend==false))
                        {
                        ...
                        }
                        }

                        (Variable names have been changed to protect the guilty) Or this *New one*:

                        void setNeedsUpdate(bool update)
                        {
                        if ((update==true))
                        NeedsUpdate=true;
                        else
                        NeedsUpdate=false;
                        }

                        C Offline
                        C Offline
                        ChunkyStool
                        wrote on last edited by
                        #64

                        I'm with you on this one! Sometimes verbosity improves readability, but there are many cases where it's just dumb. The first example is terrible:

                        bool is_queue_empty(void)
                        {
                        if (queue_length==0)
                        {
                        return true;
                        }
                        else
                        {
                        return false;
                        }
                        }

                        More code & multiple exit points -- for zero benefit???!!! X| This would be better:

                        bool is_queue_empty(void)
                        {
                        return queue_length == 0;
                        }

                        :)

                        1 Reply Last reply
                        0
                        • P patbob

                          I absolutely agree with you and consider using the a-zero-int-value-is-a-bool-false feature of C/C++ to be sloppy. Valid, but sloppy. I consider it sloppy because 0 is a meaningful (and highly useful) value for an int. However, with pointers, NULL is a meaningful value that indicates the pointer points to nothing, all other values are considered valid pointers. Using a pointer like a bool and checking if it is explicitly NULL are the same -- they are both asking if it points to anything. There is no other possible semantic interpretation. Writing code that omits an explicit comparison to NULL is also more easier to upgrade if the pointer is switched to one of the boost smart pointer classes, something we've done a fair amount of over the years. Not that the compiler doesn't catch the now-invalid comparison, but then you have to touch all that code just to get the same semantic meaning.

                          We can program with only 1's, but if all you've got are zeros, you've got nothing.

                          Y Offline
                          Y Offline
                          YvesDaoust
                          wrote on last edited by
                          #65

                          Sorry, no exception even for convenience. An integer is an integer, a pointer is a pointer and a boolean is a boolean.

                          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