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.
  • L Lost User

    You are a lucky man if that's all that makes your life miserable. Some of this is awkward, especially the second example, but where exactly is the horrible part? What damage is done? Does it not work or are there possible side effects? Does it lead to worse code being generated by the compiler? I think the first two just show a clumsy coding style, but no real harm comes from it. Except, of course, curling up your toenails when you have to read it. Usually I do the last one myself. It is at least the same way you compare any other variable (if (x == 0), so why not if (flag == true)?) and I prefer to make it absolutely clear what I want to accomplish. The compiled code remains absolutely the same, no matter how you write it. That's why I see the last one more as a matter of preferences, but not as anything important.

    And from the clouds a mighty voice spoke:
    "Smile and be happy, for it could come worse!"

    And I smiled and was happy
    And it came worse.

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

    CDP1802 wrote:

    t is at least the same way you compare any other variable (if (x == 0), so why not if (flag == true)?

    My reasoning is you could take any boolean expression, and instead of writing

    if (X)

    you could write

    if (X==true)

    to make it really clear. But you could then also write

    if ((X==true)==true)

    to make it really really clear. So I'm thinking let's drop all implied trailing "==true"'s in a mental tail call optimization. ;)

    M 1 Reply Last reply
    0
    • R RoelofDeVilliers

      CDP1802 wrote:

      t is at least the same way you compare any other variable (if (x == 0), so why not if (flag == true)?

      My reasoning is you could take any boolean expression, and instead of writing

      if (X)

      you could write

      if (X==true)

      to make it really clear. But you could then also write

      if ((X==true)==true)

      to make it really really clear. So I'm thinking let's drop all implied trailing "==true"'s in a mental tail call optimization. ;)

      M Offline
      M Offline
      Member 3687319
      wrote on last edited by
      #30

      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.

      B R 2 Replies 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;
        }

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

        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 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;
          }

          I Offline
          I Offline
          Imperion
          wrote on last edited by
          #32

          The horrors I've seen:

          void setVisible(bool isVisible)
          {
          if(isVisible.ToString().ToLower() == "true")
          {
          this.Visible = true;
          }

          if(isVisible.ToString().ToLower() == "false")
          {
          this.Visible = false;
          }
          }

          S 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
            JBoyer11
            wrote on last edited by
            #33

            I hate this code too. Maybe in C you can do this but in C# it is a travesty. What I do is create self-documenting booleans so that you write code like this:

            if (DoorIsOpen)
            {
            // Do Something
            }
            else
            {
            // Do Something else
            }

            I feel that this eliminates the need for any of the crap above. It is true that the compiler doesn't care but just remember the the point of code is so humans can understand it. If we only cared about the computer understanding it, we would all be typing 1s and 0s. Write code so that those who come after you can read it without being distracted by how horrible it is.

            "I don't believe it." "That is why you fail." -- Empire Strikes Back Shameless blog plug - www.geekswithblogs.net/jboyer

            1 Reply Last reply
            0
            • P PinballWizard

              I know that 0 is false (or FALSE) and anything else is true (or TRUE) disappointed to read through the comments ;P ... old C++ days ... since C++ defines "true" and "false" because defines the "bool" type the trick comes around when the main function must return 0 if everything is OK :omg:

              --------- Antonio

              P Offline
              P Offline
              PIEBALDconsult
              wrote on last edited by
              #34

              PinballWizard wrote:

              the main function must return 0 if everything is OK

              That's why zero should mean true. :sigh:

              1 Reply Last reply
              0
              • B BobJanova

                And yet that style of testing for non-null is the standard in, for example, JavaScript. (Personally I have no problem with it in C either, for pointer or unsigned types ... with signed values it's bad because as pointed out someone could potentially switch negative values' interpretation out from under you.) When comparing against something which is (semantically or definitively, depending on your language) a boolean, though, there's absolutely no reason to make the reader parse more text before he can understand your statement. Adding the ' == true' provides zero clarification value, as anyone who vaguely knows the language knows that if tests check for a true value. In your example here, adding the ' != NULL' does provide a little clarification, so it's pretty much a value-neutral stylistic choice to add it or not. (Someone might suggest that NULL could evaluate to true, but anyone who makes that #define is far more culpable for any confusion than the person who writes the check you put here, and in any professional context that won't be the case.)

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

                BobJanova wrote:

                Adding the ' == true' provides zero clarification value

                Exactly! Not only that, it also adds the potential for a catastrophic typo: =true instead of ==true. I'd even go so far as to include comparisons to user-defined symbols that represent boolean states, such as TRUE and FALSE: if if(x) is not equivalent to if(x==TRUE), then the definitions are wrong, since they do not adhere to the rules of boolean logic! In that case not the comparison needs to be 'fixed', but the definitions!

                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;
                  }

                  S Offline
                  S Offline
                  Stefan_Lang
                  wrote on last edited by
                  #36

                  Let's see... The first example I don't like - not for the if statement, but for the premature returns! Personally, I'd make it a one-liner, but I don't consider it all that horrible apart from the returns. The second ... well you could argue it's slightly more readable for inexperienced programmers, but if that is your purpose then you should write an if/else statement, not use ?:. The next is a double horror for comparing to boolean constants and unnecessary nesting, but I'd forgive the nesting for the off-chance of later maintenance introducing additional statements that depend on only the first condition. The last ... I suppose if you need to be able to run your code through really old C compilers that don't have their own built-in definitions of bool, true and false, then it makes sense not to assign one boolean variable blindly to another, but instead make an if/else statement to catch the case where the argument is neither true nor false. But even then, ==true is horrible. So, in short, all of the examples are indeed bad style, IMHO, but I agree with the others that no harm is done, except maybe a minor hit in maintenance effort for posting it in the Hall of Shame. ;) None of this will cause inefficiency either, since compilers are smart enough to produce efficient code even from that kind of code.

                  1 Reply Last reply
                  0
                  • I Imperion

                    The horrors I've seen:

                    void setVisible(bool isVisible)
                    {
                    if(isVisible.ToString().ToLower() == "true")
                    {
                    this.Visible = true;
                    }

                    if(isVisible.ToString().ToLower() == "false")
                    {
                    this.Visible = false;
                    }
                    }

                    S Offline
                    S Offline
                    Stefan_Lang
                    wrote on last edited by
                    #37

                    :wtf: You're making this up, aren't you? :omg:

                    I 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;
                      }

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

                      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 1 Reply Last reply
                      0
                      • S Stefan_Lang

                        :wtf: You're making this up, aren't you? :omg:

                        I Offline
                        I Offline
                        Imperion
                        wrote on last edited by
                        #39

                        I wish I was making this up. X| Although it's good for a laugh (then a cry) when we go in to fix a bug in his old modules.

                        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;
                          }

                          R Offline
                          R Offline
                          Rick Shaub
                          wrote on last edited by
                          #40

                          Maybe he saw this boolean[^], got confused, and wanted to "make sure".

                          S 1 Reply Last reply
                          0
                          • L Lost User

                            Screw the compiler. It takes longer to read and understand, therefore it sucks.

                            F Offline
                            F Offline
                            Fabio Franco
                            wrote on last edited by
                            #41

                            And it obviously makes the reader scared of what else might come from that code who's developer can't understand even a booleans...

                            "To alcohol! The cause of, and solution to, all of life's problems" - Homer Simpson

                            M 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;
                              }

                              R Offline
                              R Offline
                              rcampbell12
                              wrote on last edited by
                              #42

                              Hey, you're coding in a language that I don't use, but I'm totally with you. This is one of my pet peeves, too. One of my languages is Visual FoxPro, which has the "Immediate IF" ternary function, IIF: IIF(expr, a, b) If expr is true, a is returned, otherwise b is returned. So what I see is people doing this: MyBoolVar = IIF(SomeVar = 2, .t., .f.) Which could be simplified to: MyBoolVar = SomeVar = 2 Much cleaner. Or they expand it into a regular IF statement similar to what you posted. When I see this it does worry me. If programming should result from logical thinking and a programmer has trouble understanding logical values (boolean values), then should we wonder about the rest of their skills?

                              1 Reply Last reply
                              0
                              • R Rick Shaub

                                Maybe he saw this boolean[^], got confused, and wanted to "make sure".

                                S Offline
                                S Offline
                                Stefan_Lang
                                wrote on last edited by
                                #43

                                Wow - that link is worthy of a top position in the Hall of Shame all by itself! :omg:

                                1 Reply Last reply
                                0
                                • L Lost User

                                  Yes, I suppose this simply comes from the old C++ days where there was no boolean type. To avoid side effects or compiler specific behavior, I always explicitly specified what I was testing. But I would write it like this:

                                  if((flag1 == true) &&
                                  (flag2 == true) &&
                                  (flag3 == true))
                                  {
                                  ...
                                  }

                                  Usually it does not look so uniform. If I really had so many different flags, I would think about using a flag word and testing all flags in one go.

                                  And from the clouds a mighty voice spoke:
                                  "Smile and be happy, for it could come worse!"

                                  And I smiled and was happy
                                  And it came worse.

                                  K Offline
                                  K Offline
                                  Kabwla Phone
                                  wrote on last edited by
                                  #44

                                  (edit: I posted this as a reply to a message that is now now longer there, oh well) I do not write out the boolean, but I do write each condition on a new line. In addition to that, I start the new line with the operator, this way, it is very easy to see at the beginning of the line that it is a continuation of the previous line, and what the operation is:

                                  if( flag1
                                  && (someOtherFlagThatWillSqrewWithTheLayout == MagicNumbers.Ten)
                                  && (flag3 == somethingElseCompletely))
                                  {
                                  ...
                                  }

                                  I use this style with anything that will make a line of code too long:

                                  //Contrived Deep Nesting, line too long
                                  var firstChildRow= SomeTypedDataSetWithSillyLongNameThatFillsTheEntireCodeWindow.Tables[0].ChildRelations[0].ChildTable.Rows[0];
                                  //Broken up for readability. Note that I start with the 'dot'.
                                  var firstChildRow= SomeTypedDataSetWithSillyLongNameThatFillsTheEntireCodeWindow
                                  .Tables[0]
                                  .ChildRelations[0]
                                  .ChildTable
                                  .Rows[0];

                                  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;
                                    }

                                    N Offline
                                    N Offline
                                    Nunnenkamp
                                    wrote on last edited by
                                    #45

                                    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;
                                    }

                                    F Y 2 Replies 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;
                                      }

                                      F Offline
                                      F Offline
                                      fjdiewornncalwe
                                      wrote on last edited by
                                      #46

                                      The second is better than the first. At least if you're going to set the value in this ridiculous fashion, make sure that it worked. :)

                                      I wasn't, now I am, then I won't be anymore.

                                      1 Reply Last reply
                                      0
                                      • L Lost User

                                        Yes, I suppose this simply comes from the old C++ days where there was no boolean type. To avoid side effects or compiler specific behavior, I always explicitly specified what I was testing. But I would write it like this:

                                        if((flag1 == true) &&
                                        (flag2 == true) &&
                                        (flag3 == true))
                                        {
                                        ...
                                        }

                                        Usually it does not look so uniform. If I really had so many different flags, I would think about using a flag word and testing all flags in one go.

                                        And from the clouds a mighty voice spoke:
                                        "Smile and be happy, for it could come worse!"

                                        And I smiled and was happy
                                        And it came worse.

                                        A Offline
                                        A Offline
                                        Addy Tas
                                        wrote on last edited by
                                        #47

                                        I came from the same dark ages and indeed untill some time ago i also had the tendency to check the boolean value. Particularly the BOOL was a nasty one as you could (with good sense) only check that to FALSE. One other 'trick' i got used to apply was swapping the variable and the value E.g.

                                        if(FALSE != flag)
                                        {

                                        Logically this seems a bit odd but then again it did protect me against typo's like:

                                        if( flag = FALSE)
                                        {

                                        Today this will generate a compiler warning but that has not always been the case and if you have a special vendor type compiler; you may still face the same. Why check on FALSE? Simple; that was defined (as 0), any one could set the BOOL to TRUE, 1, 2 etc. Don't you love the compilers of today? Or better yet, those of tomorrow? Cheers, AT

                                        Cogito ergo sum

                                        1 Reply Last reply
                                        0
                                        • P PIEBALDconsult

                                          CDP1802 wrote:

                                          why not if (flag == true)?

                                          Indeed, I prefer that when writing in C. One thing that drives me nuts with C is reading things like:

                                          char* s = ...

                                          if ( s ) ...

                                          :mad:

                                          A Offline
                                          A Offline
                                          Addy Tas
                                          wrote on last edited by
                                          #48

                                          That in combination with the inabiliy to properly initialize a variable has ruined more than one day... Cheers, AT

                                          Cogito ergo sum

                                          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