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. if else Style

if else Style

Scheduled Pinned Locked Moved The Lounge
tutorial
79 Posts 33 Posters 5 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.
  • B BernardIE5317

    Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS

    P Offline
    P Offline
    Peter Kelley 2021
    wrote on last edited by
    #61

    This is a good question! It happens in real life and doesn't get discussed much though! I recommend that you do *not* put in the extra test, because... > If there is any future maintenance involving a change to the condition the future programmer will need to review both conditions. Extra comprehension, extra code - more likely an error or misunderstanding. > a comment would serve the same purpose - and even can be removed safely > ? If you have both tests, then ask what's the "else" for? My experience - I've seen this done in the past, and it just trips up future programmer and confuses the human reader. [my edit: - Absolutely agree with Iacopo Vettori's comment - use 'Assert' for such cases]

    1 Reply Last reply
    0
    • B BernardIE5317

      Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS

      J Offline
      J Offline
      John Wellbelove
      wrote on last edited by
      #62

      Every place I've worked that used C/C++ in the past 35 years dictated this style (and it's my style of choice). if () { } else if { } else { }

      1 Reply Last reply
      0
      • B BernardIE5317

        Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS

        M Offline
        M Offline
        MikeCO10
        wrote on last edited by
        #63

        As you wrote it, the 1st style is correct. Meaning an expression evaluates to true or false. The else if injects a potential question when re-reading the code that another possibility exists. If it were if(boolvar==true)..., there may be cases where the else if is appropriate.

        1 Reply Last reply
        0
        • B BernardIE5317

          Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS

          M Offline
          M Offline
          Matt Bond
          wrote on last edited by
          #64

          For short, simple IF/ELSE statements, I do not use the ELSE IF (false) because it is unnecessary. If there are a large number of statements inside the IF block, then I'll use

          IF () {
          ...
          }
          else //Not {
          ...
          }

          This allows me to document the code with a simple comment since the IF test is too far away from the ELSE.

          Bond Keep all things as simple as possible, but no simpler. -said someone, somewhere

          1 Reply Last reply
          0
          • T trønderen

            I do hope that the "==true" and "==false" are not meant literally! A programmer comparing a logical expression against "true" or "false" have not understood what is meant by a logical expression. I wonder how many of those programming that way also speak that way! "If you have a moment to spare is true, I want a talk with you", or "If the door is unlocked is false, you'll find the key under the door mat" - noone that I know speaks that way. I have met a few programmers who program that way, but I never heard any of them speak with "is true" or "is false".

            Religious freedom is the freedom to say that two plus two make five.

            M Offline
            M Offline
            Matt Bond
            wrote on last edited by
            #65

            I have frequently seen programmers from India use

            if (variable == true){...}

            in their code. I really don't understand it. But to be fair, their variables names do not make it clear that it's a Boolean value. All of my Boolean variables' names are a Yes/No question (IsValid, DoneProcessing, DoUseQuotes, etc.) so it's obviously a Boolean. When your Boolean variables are named poorly (Validation, Finish, Quotes, etc.), then you need the "== Boolean" in order to know what is going on.

            Bond Keep all things as simple as possible, but no simpler. -said someone, somewhere

            1 Reply Last reply
            0
            • D Daniel Pfeffer

              As others have said, it depends on the context. I prefer a ternary operator if I must choose between returning one of two results:

              Foo foo = (condition ? Foo1 : Foo2);

              For choosing different actions, I prefer the if/then/else style, even if it would be possible to write this as a ternary expression:

              if (condition)
              {
              expressions1;
              }
              else
              {
              expressions2;
              }

              A "cascading" if/then/else is useful for subordinate cases:

              if (condition1)
              {
              expressions1;
              }
              else
              {
              if (condition2)
              {
              expressions2;
              }
              else
              {
              expressions3;
              }
              }

              Note that there is angoing debate whether good style requires that one wrap even single expressions in curly brackets. ( {...} }. If is usually not required by the language, but can help clarify the flow. Note that there are cases where a "cascading ternary operator" can also be useful, and actually clearer than the "cascading if/then/else".

              Freedom is the freedom to say that two plus two make four. If that is granted, all else follows. -- 6079 Smith W.

              M Offline
              M Offline
              Matt Bond
              wrote on last edited by
              #66

              In languages were the braces (other other syntax) is not required to block out an IF or ELSE block of code, I have seen many bugs where someone got it wrong, or edited it much later incorrectly. In my code reviews, I enforce having them for all cases because it's impossible to get wrong were the code block starts and stops; there is no interpretation of non-visible cues needed.

              Bond Keep all things as simple as possible, but no simpler. -said someone, somewhere

              1 Reply Last reply
              0
              • B BernardIE5317

                Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS

                J Offline
                J Offline
                jschell
                wrote on last edited by
                #67

                BernardIE5317 wrote:

                if(expression == true) {...}

                I had forgotten another variance on mandating usage.

                if(true == expression)

                Some C++ coders insisted on that because, the possibility existed that one might code the following.

                if(expression = true)

                And that is valid in C++. Myself C++ programmers not controlling the scope of the their memory allocations was always, and still is, much more of a significant problem.

                A 1 Reply Last reply
                0
                • C charlieg

                  yeah, the brace on the same line makes me want to puke.

                  Charlie Gilley “They who can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety.” BF, 1759 Has never been more appropriate.

                  N Offline
                  N Offline
                  Norm Powroz
                  wrote on last edited by
                  #68

                  Wholeheartedly agree! Having the braces on separate lines makes it so much easier to determine where the then/else clauses begin and end. Lining them up vertically at each indentation level also means you can easily see what goes with what, such as: if (expression) { // then result if (other condition) { // Other condition then result } else { // other condition else result } } else { // else result } I really hate code that puts all the opening braces on the if (expression) line, or the "else" line. Programmers who don't believe in clarity of their code should be banned from the practice. Don't forget -- comments can also help a lot in improving clarity.

                  T 1 Reply Last reply
                  0
                  • N Norm Powroz

                    Wholeheartedly agree! Having the braces on separate lines makes it so much easier to determine where the then/else clauses begin and end. Lining them up vertically at each indentation level also means you can easily see what goes with what, such as: if (expression) { // then result if (other condition) { // Other condition then result } else { // other condition else result } } else { // else result } I really hate code that puts all the opening braces on the if (expression) line, or the "else" line. Programmers who don't believe in clarity of their code should be banned from the practice. Don't forget -- comments can also help a lot in improving clarity.

                    T Offline
                    T Offline
                    trønderen
                    wrote on last edited by
                    #69

                    Norm Powroz wrote:

                    Having the braces on separate lines makes it so much easier to determine where the then/else clauses begin and end.

                    You have indentation for that, don't you? If you indent neither of the braces, they do not enforce the indentation, but blurs both the indentation and the keyword causing the indentation. If you indent both, the keyword is 'revealed'. And the block is extended by two two lines, making it more prominent. I think that making 'the indenting keyword' more visible (by avoiding the blurring opening brace immediately below it) is a good thing. Indenting before the opening brace is logically inconsistent - so the brace should be un-indented, at the line of the if / while / ... . Also, when you read e.g. an if, and the line ends abruptly, with no explanation, you should rather include the brace to indicate: There is an explanation - this brace tells that a block is following! The closing brace on a separate indented line ensures that the indented block is at least two lines long. That should be enough for everybody, to make sure that the block is easily identified. I think un-indented braces blur the indented block, rather than enforcing it as it should.

                    Religious freedom is the freedom to say that two plus two make five.

                    1 Reply Last reply
                    0
                    • B BernardIE5317

                      Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS

                      S Offline
                      S Offline
                      Stacy Dudovitz
                      wrote on last edited by
                      #70

                      In reading all of the responses, I'm quite surprised that the only alternative mentioned was the tertiary operator (?: ). While it's simple to respond 'context dependent' as I saw in some of the replies, I think maybe it would help to spell out the concerns as well as offer up more choices. Let's start with the elephant in the room... readability and maintainability. They both go hand in hand to answer the question "what are you trying to do or say in the code?" In addition, some of the choices can lead to both bugs and code creep. Let's start with if/else as a potential solution to express a/the logical path to traverse. A couple of simple rules would help (these are *my* rules, some may be obvious, but some are what I call 'Where's the curly brace' religious preferences. Take everything I write here are my own style rather than engage in religiosity).

                      if (condition 1)
                      {
                      // do something 1
                      }
                      else if (condition 2)
                      {
                      // do something 2
                      }
                      else
                      {
                      // do something 3
                      }

                      I always include the curly braces to ensure that scope is honored i.e. what code is executed based on which condition is met. Too often I've see this:

                      if (condition 1)
                      // do something 1
                      else if (condition 2)
                      // do something 2
                      else
                      // do something 3

                      The problem here is if another author comes in to add/maintain the code, and adds a second line of execution to one of the conditions. If that author forgets to now add the curly braces to enclose scope, bad things happen.

                      if (condition 1)
                      // do something 1
                      else if (condition 2)
                      // do something 2A
                      // do something 2B <-- we've exited the scope of the if/else clause. Ooops!
                      else
                      // do something 3

                      In addition, the whole Nickleback induced hatred the tertiary operator hails back to a late 70's bug introduced in a version (or couple of versions) of the Whitesmiths C compiler, and has since become lore. If we are striving for readability, then:

                      if (condition) ? "do one thing" : "do the other thing";

                      If you are vehemently opposed to this, chances are you also avoid the null coalescing as well as other similar constructs:

                      char *s = null;
                      char *t = null;
                      ...

                      t = s ? "some string" : "some default";

                      But really, is this the only way to proceed? How about:

                      switch (operand)
                      {
                      case 1:
                      // do something case 1
                      break;
                      case 2:
                      // do something case 2
                      break;
                      case 3:
                      // do something case 3

                      J E 2 Replies Last reply
                      0
                      • S Stacy Dudovitz

                        In reading all of the responses, I'm quite surprised that the only alternative mentioned was the tertiary operator (?: ). While it's simple to respond 'context dependent' as I saw in some of the replies, I think maybe it would help to spell out the concerns as well as offer up more choices. Let's start with the elephant in the room... readability and maintainability. They both go hand in hand to answer the question "what are you trying to do or say in the code?" In addition, some of the choices can lead to both bugs and code creep. Let's start with if/else as a potential solution to express a/the logical path to traverse. A couple of simple rules would help (these are *my* rules, some may be obvious, but some are what I call 'Where's the curly brace' religious preferences. Take everything I write here are my own style rather than engage in religiosity).

                        if (condition 1)
                        {
                        // do something 1
                        }
                        else if (condition 2)
                        {
                        // do something 2
                        }
                        else
                        {
                        // do something 3
                        }

                        I always include the curly braces to ensure that scope is honored i.e. what code is executed based on which condition is met. Too often I've see this:

                        if (condition 1)
                        // do something 1
                        else if (condition 2)
                        // do something 2
                        else
                        // do something 3

                        The problem here is if another author comes in to add/maintain the code, and adds a second line of execution to one of the conditions. If that author forgets to now add the curly braces to enclose scope, bad things happen.

                        if (condition 1)
                        // do something 1
                        else if (condition 2)
                        // do something 2A
                        // do something 2B <-- we've exited the scope of the if/else clause. Ooops!
                        else
                        // do something 3

                        In addition, the whole Nickleback induced hatred the tertiary operator hails back to a late 70's bug introduced in a version (or couple of versions) of the Whitesmiths C compiler, and has since become lore. If we are striving for readability, then:

                        if (condition) ? "do one thing" : "do the other thing";

                        If you are vehemently opposed to this, chances are you also avoid the null coalescing as well as other similar constructs:

                        char *s = null;
                        char *t = null;
                        ...

                        t = s ? "some string" : "some default";

                        But really, is this the only way to proceed? How about:

                        switch (operand)
                        {
                        case 1:
                        // do something case 1
                        break;
                        case 2:
                        // do something case 2
                        break;
                        case 3:
                        // do something case 3

                        J Offline
                        J Offline
                        jschell
                        wrote on last edited by
                        #71

                        Stacy Dudovitz wrote:

                        If that author forgets to now add the curly braces to enclose scope, bad things happen.

                        So not only coding now to guess at the competence of future programmers but also presuming that comprehensive unit testing will not happen?

                        S 1 Reply Last reply
                        0
                        • J jschell

                          Stacy Dudovitz wrote:

                          If that author forgets to now add the curly braces to enclose scope, bad things happen.

                          So not only coding now to guess at the competence of future programmers but also presuming that comprehensive unit testing will not happen?

                          S Offline
                          S Offline
                          Stacy Dudovitz
                          wrote on last edited by
                          #72

                          To the first question about competence, that may be a bit harsh. We are, after all, human beings, and as such, even the best of us make mistakes. To be clear, while some mistakes can be attributed to competency levels and/or experience, I've also seen errors due to time pressure from the decisions makers, long hours of debugging a nasty problem, or other factors which can contribute to bugs. Hence, my suggestion/recommendation falls more in line with defensive coding rather than assuming that everyone that is not me is an idiot. Your mileage may vary on that point. With regards to unit testing, even in shops where unit testing is mandated as part of the development process (again, until a time deadline or other external factors discourage the practice in light of external pressures), my experience has been that often unit testing is more to tick off a checkbox than to actually produce maintainable and reliable code. Writing proper unit test code is an artform unto itself, and is predicated on other practices such as one method should encompass exactly one function. (Lets not split hairs on the triumvirate of the types of testing i.e. unit, system and integration tests. In this case I am referring to all three under the single banner of 'unit testing'.) Bottom line, whatever practice you or your shop choose to implement, it should be purposeful and consistent. My post here was to offer a more thorough response to the original question.

                          J 1 Reply Last reply
                          0
                          • B BernardIE5317

                            Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS

                            E Offline
                            E Offline
                            englebart
                            wrote on last edited by
                            #73

                            Do not attempt the extra check if you are dealing with floating points. You might really need the extra ELSE clause. if (x > 1.0) { } else if (x <= 1.0) { } else { // yes you can reach this throw wtf; } What are possible values of x?

                            S 1 Reply Last reply
                            0
                            • E englebart

                              Do not attempt the extra check if you are dealing with floating points. You might really need the extra ELSE clause. if (x > 1.0) { } else if (x <= 1.0) { } else { // yes you can reach this throw wtf; } What are possible values of x?

                              S Offline
                              S Offline
                              Stacy Dudovitz
                              wrote on last edited by
                              #74

                              Disagree! (contingent on compiler switches set, of course :) )

                              else {
                              // yes you can reach this
                              throw wtf;
                              }

                              if (x == NaN) or some similar hairy answer, the compiler (again, with the correct compilation switches set) will automagically throw an exception. Sidebar: One would NOT want to set said same switches on an embedded piece of code, since typically exception handling is turned off. Therefore, one would NOT, in such an instance wish to throw wtf.

                              E 1 Reply Last reply
                              0
                              • J jschell

                                BernardIE5317 wrote:

                                if(expression == true) {...}

                                I had forgotten another variance on mandating usage.

                                if(true == expression)

                                Some C++ coders insisted on that because, the possibility existed that one might code the following.

                                if(expression = true)

                                And that is valid in C++. Myself C++ programmers not controlling the scope of the their memory allocations was always, and still is, much more of a significant problem.

                                A Offline
                                A Offline
                                Alister Morton
                                wrote on last edited by
                                #75

                                jschell wrote:

                                if(true == expression)

                                sometimes referred to as Yoda formatting.

                                1 Reply Last reply
                                0
                                • S Stacy Dudovitz

                                  To the first question about competence, that may be a bit harsh. We are, after all, human beings, and as such, even the best of us make mistakes. To be clear, while some mistakes can be attributed to competency levels and/or experience, I've also seen errors due to time pressure from the decisions makers, long hours of debugging a nasty problem, or other factors which can contribute to bugs. Hence, my suggestion/recommendation falls more in line with defensive coding rather than assuming that everyone that is not me is an idiot. Your mileage may vary on that point. With regards to unit testing, even in shops where unit testing is mandated as part of the development process (again, until a time deadline or other external factors discourage the practice in light of external pressures), my experience has been that often unit testing is more to tick off a checkbox than to actually produce maintainable and reliable code. Writing proper unit test code is an artform unto itself, and is predicated on other practices such as one method should encompass exactly one function. (Lets not split hairs on the triumvirate of the types of testing i.e. unit, system and integration tests. In this case I am referring to all three under the single banner of 'unit testing'.) Bottom line, whatever practice you or your shop choose to implement, it should be purposeful and consistent. My post here was to offer a more thorough response to the original question.

                                  J Offline
                                  J Offline
                                  jschell
                                  wrote on last edited by
                                  #76

                                  Stacy Dudovitz wrote:

                                  often unit testing is more to tick off a checkbox

                                  That can be solved with required code reviews and required code coverage metrics.

                                  1 Reply Last reply
                                  0
                                  • S Stacy Dudovitz

                                    Disagree! (contingent on compiler switches set, of course :) )

                                    else {
                                    // yes you can reach this
                                    throw wtf;
                                    }

                                    if (x == NaN) or some similar hairy answer, the compiler (again, with the correct compilation switches set) will automagically throw an exception. Sidebar: One would NOT want to set said same switches on an embedded piece of code, since typically exception handling is turned off. Therefore, one would NOT, in such an instance wish to throw wtf.

                                    E Offline
                                    E Offline
                                    englebart
                                    wrote on last edited by
                                    #77

                                    The OP never mentioned language or compilers. Some compilers for whatever language may not support those options. It was a general stylistic question. Most compilers (and forums) won’t even warn when you use assignment operator instead of comparison operator. 😊

                                    1 Reply Last reply
                                    0
                                    • S Stacy Dudovitz

                                      In reading all of the responses, I'm quite surprised that the only alternative mentioned was the tertiary operator (?: ). While it's simple to respond 'context dependent' as I saw in some of the replies, I think maybe it would help to spell out the concerns as well as offer up more choices. Let's start with the elephant in the room... readability and maintainability. They both go hand in hand to answer the question "what are you trying to do or say in the code?" In addition, some of the choices can lead to both bugs and code creep. Let's start with if/else as a potential solution to express a/the logical path to traverse. A couple of simple rules would help (these are *my* rules, some may be obvious, but some are what I call 'Where's the curly brace' religious preferences. Take everything I write here are my own style rather than engage in religiosity).

                                      if (condition 1)
                                      {
                                      // do something 1
                                      }
                                      else if (condition 2)
                                      {
                                      // do something 2
                                      }
                                      else
                                      {
                                      // do something 3
                                      }

                                      I always include the curly braces to ensure that scope is honored i.e. what code is executed based on which condition is met. Too often I've see this:

                                      if (condition 1)
                                      // do something 1
                                      else if (condition 2)
                                      // do something 2
                                      else
                                      // do something 3

                                      The problem here is if another author comes in to add/maintain the code, and adds a second line of execution to one of the conditions. If that author forgets to now add the curly braces to enclose scope, bad things happen.

                                      if (condition 1)
                                      // do something 1
                                      else if (condition 2)
                                      // do something 2A
                                      // do something 2B <-- we've exited the scope of the if/else clause. Ooops!
                                      else
                                      // do something 3

                                      In addition, the whole Nickleback induced hatred the tertiary operator hails back to a late 70's bug introduced in a version (or couple of versions) of the Whitesmiths C compiler, and has since become lore. If we are striving for readability, then:

                                      if (condition) ? "do one thing" : "do the other thing";

                                      If you are vehemently opposed to this, chances are you also avoid the null coalescing as well as other similar constructs:

                                      char *s = null;
                                      char *t = null;
                                      ...

                                      t = s ? "some string" : "some default";

                                      But really, is this the only way to proceed? How about:

                                      switch (operand)
                                      {
                                      case 1:
                                      // do something case 1
                                      break;
                                      case 2:
                                      // do something case 2
                                      break;
                                      case 3:
                                      // do something case 3

                                      E Offline
                                      E Offline
                                      englebart
                                      wrote on last edited by
                                      #78

                                      Agree on the curly braces. There was someone who did a lot of research about which if/else brace pattern worked best for automated merging, but I can never find it.

                                      1 Reply Last reply
                                      0
                                      • B BernardIE5317

                                        Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS

                                        H Offline
                                        H Offline
                                        hpcoder2
                                        wrote on last edited by
                                        #79

                                        Hell no! If you must put the second conditional for documentation purposes, make it a comment if (cond) ... else // if (!cond) ... or if (cond) ... else // cond ... I've seen that style used for conditional compilation, not so much for braces. #if cond ... #else ... #endif //cond

                                        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